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
.util
.AbstractList
;
25 import java
.util
.HashMap
;
26 import java
.util
.Iterator
;
28 import java
.util
.Vector
;
30 import android
.accounts
.Account
;
31 import android
.accounts
.AccountManager
;
32 import android
.accounts
.OnAccountsUpdateListener
;
33 import android
.app
.NotificationManager
;
34 import android
.app
.PendingIntent
;
35 import android
.app
.Service
;
36 import android
.content
.Intent
;
37 import android
.os
.Binder
;
38 import android
.os
.Handler
;
39 import android
.os
.HandlerThread
;
40 import android
.os
.IBinder
;
41 import android
.os
.Looper
;
42 import android
.os
.Message
;
43 import android
.os
.Process
;
44 import android
.support
.v4
.app
.NotificationCompat
;
45 import android
.util
.Pair
;
46 import android
.webkit
.MimeTypeMap
;
48 import com
.owncloud
.android
.R
;
49 import com
.owncloud
.android
.authentication
.AccountUtils
;
50 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
51 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
52 import com
.owncloud
.android
.datamodel
.OCFile
;
53 import com
.owncloud
.android
.db
.DbHandler
;
54 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
55 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
56 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
57 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
58 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
59 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
60 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
61 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
62 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
63 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
64 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
65 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
66 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
67 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
68 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
70 import com
.owncloud
.android
.operations
.UploadFileOperation
;
71 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
72 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
73 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
74 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
75 import com
.owncloud
.android
.utils
.UriUtils
;
78 public class FileUploader
extends Service
79 implements OnDatatransferProgressListener
, OnAccountsUpdateListener
{
81 private static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
82 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
83 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
84 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
85 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
86 public static final String EXTRA_LINKED_TO_PATH
= "LINKED_TO";
87 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
89 public static final String KEY_FILE
= "FILE";
90 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
91 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
92 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
94 public static final String KEY_ACCOUNT
= "ACCOUNT";
96 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
97 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
98 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
99 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
101 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
102 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
103 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
105 public static final int UPLOAD_SINGLE_FILE
= 0;
106 public static final int UPLOAD_MULTIPLE_FILES
= 1;
108 private static final String TAG
= FileUploader
.class.getSimpleName();
110 private Looper mServiceLooper
;
111 private ServiceHandler mServiceHandler
;
112 private IBinder mBinder
;
113 private OwnCloudClient mUploadClient
= null
;
114 private Account mCurrentAccount
= null
;
115 private FileDataStorageManager mStorageManager
;
117 private IndexedForest
<UploadFileOperation
> mPendingUploads
= new IndexedForest
<UploadFileOperation
>();
118 private UploadFileOperation mCurrentUpload
= null
;
120 private NotificationManager mNotificationManager
;
121 private NotificationCompat
.Builder mNotificationBuilder
;
122 private int mLastPercent
;
124 private static final String MIME_TYPE_PDF
= "application/pdf";
125 private static final String FILE_EXTENSION_PDF
= ".pdf";
128 public static String
getUploadFinishMessage() {
129 return FileUploader
.class.getName() + UPLOAD_FINISH_MESSAGE
;
133 * Checks if an ownCloud server version should support chunked uploads.
135 * @param version OwnCloud version instance corresponding to an ownCloud
137 * @return 'True' if the ownCloud server with version supports chunked
140 * TODO - move to OCClient
142 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
143 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
147 * Service initialization
150 public void onCreate() {
152 Log_OC
.d(TAG
, "Creating service");
153 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
154 HandlerThread thread
= new HandlerThread("FileUploaderThread",
155 Process
.THREAD_PRIORITY_BACKGROUND
);
157 mServiceLooper
= thread
.getLooper();
158 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
159 mBinder
= new FileUploaderBinder();
161 // add AccountsUpdatedListener
162 AccountManager am
= AccountManager
.get(getApplicationContext());
163 am
.addOnAccountsUpdatedListener(this, null
, false
);
170 public void onDestroy() {
171 Log_OC
.v(TAG
, "Destroying service" );
173 mServiceHandler
= null
;
174 mServiceLooper
.quit();
175 mServiceLooper
= null
;
176 mNotificationManager
= null
;
178 // remove AccountsUpdatedListener
179 AccountManager am
= AccountManager
.get(getApplicationContext());
180 am
.removeOnAccountsUpdatedListener(this);
187 * Entry point to add one or several files to the queue of uploads.
189 * New uploads are added calling to startService(), resulting in a call to
190 * this method. This ensures the service will keep on working although the
191 * caller activity goes away.
194 public int onStartCommand(Intent intent
, int flags
, int startId
) {
195 Log_OC
.d(TAG
, "Starting command with id " + startId
);
197 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
198 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
199 Log_OC
.e(TAG
, "Not enough information provided in intent");
200 return Service
.START_NOT_STICKY
;
202 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
203 if (uploadType
== -1) {
204 Log_OC
.e(TAG
, "Incorrect upload type provided");
205 return Service
.START_NOT_STICKY
;
207 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
208 if (!AccountUtils
.exists(account
, getApplicationContext())) {
209 return Service
.START_NOT_STICKY
;
212 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
213 OCFile
[] files
= null
;
214 if (uploadType
== UPLOAD_SINGLE_FILE
) {
216 if (intent
.hasExtra(KEY_FILE
)) {
217 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
220 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
221 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
222 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
225 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
227 if (intent
.hasExtra(KEY_FILE
)) {
228 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
236 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
237 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
238 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
242 FileDataStorageManager storageManager
= new FileDataStorageManager(account
,
243 getContentResolver());
245 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
246 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
247 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
249 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
250 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
251 return Service
.START_NOT_STICKY
;
253 } else if (!intent
.hasExtra(KEY_FILE
)) {
254 if (localPaths
== null
) {
255 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
256 return Service
.START_NOT_STICKY
;
258 if (remotePaths
== null
) {
259 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
260 return Service
.START_NOT_STICKY
;
262 if (localPaths
.length
!= remotePaths
.length
) {
263 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
264 return Service
.START_NOT_STICKY
;
267 files
= new OCFile
[localPaths
.length
];
268 for (int i
= 0; i
< localPaths
.length
; i
++) {
269 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
],
270 ((mimeTypes
!= null
) ? mimeTypes
[i
] : null
));
271 if (files
[i
] == null
) {
272 // TODO @andomaex add failure Notification
273 return Service
.START_NOT_STICKY
;
278 OwnCloudVersion ocv
= AccountUtils
.getServerVersion(account
);
280 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
281 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
282 String uploadKey
= null
;
283 UploadFileOperation newUpload
= null
;
285 for (int i
= 0; i
< files
.length
; i
++) {
286 newUpload
= new UploadFileOperation(
291 forceOverwrite
, localAction
,
292 getApplicationContext()
295 newUpload
.setRemoteFolderToBeCreated();
297 newUpload
.addDatatransferProgressListener(this);
298 newUpload
.addDatatransferProgressListener((FileUploaderBinder
) mBinder
);
299 Pair
<String
, String
> putResult
= mPendingUploads
.putIfAbsent(
300 account
, files
[i
].getRemotePath(), newUpload
302 if (putResult
!= null
) {
303 uploadKey
= putResult
.first
;
304 requestedUploads
.add(uploadKey
);
305 } // else, file already in the queue of uploads; don't repeat the request
308 } catch (IllegalArgumentException e
) {
309 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
310 return START_NOT_STICKY
;
312 } catch (IllegalStateException e
) {
313 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
314 return START_NOT_STICKY
;
316 } catch (Exception e
) {
317 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
318 return START_NOT_STICKY
;
322 if (requestedUploads
.size() > 0) {
323 Message msg
= mServiceHandler
.obtainMessage();
325 msg
.obj
= requestedUploads
;
326 mServiceHandler
.sendMessage(msg
);
328 return Service
.START_NOT_STICKY
;
332 * Provides a binder object that clients can use to perform operations on
333 * the queue of uploads, excepting the addition of new files.
335 * Implemented to perform cancellation, pause and resume of existing
339 public IBinder
onBind(Intent arg0
) {
344 * Called when ALL the bound clients were onbound.
347 public boolean onUnbind(Intent intent
) {
348 ((FileUploaderBinder
)mBinder
).clearListeners();
349 return false
; // not accepting rebinding (default behaviour)
353 public void onAccountsUpdated(Account
[] accounts
) {
354 // Review current upload, and cancel it if its account doen't exist
355 if (mCurrentUpload
!= null
&&
356 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
357 mCurrentUpload
.cancel();
359 // The rest of uploads are cancelled when they try to start
363 * Binder to let client components to perform operations on the queue of
366 * It provides by itself the available operations.
368 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
371 * Map of listeners that will be reported about progress of uploads from a
372 * {@link FileUploaderBinder} instance
374 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
=
375 new HashMap
<String
, OnDatatransferProgressListener
>();
378 * Cancels a pending or current upload of a remote file.
380 * @param account ownCloud account where the remote file will be stored.
381 * @param file A file in the queue of pending uploads
383 public void cancel(Account account
, OCFile file
) {
384 Pair
<UploadFileOperation
, String
> removeResult
= mPendingUploads
.remove(account
, file
.getRemotePath());
385 UploadFileOperation upload
= removeResult
.first
;
386 if (upload
!= null
) {
389 if (mCurrentUpload
!= null
&& mCurrentAccount
!= null
&&
390 mCurrentUpload
.getRemotePath().startsWith(file
.getRemotePath()) &&
391 account
.name
.equals(mCurrentAccount
.name
)) {
392 mCurrentUpload
.cancel();
398 * Cancels all the uploads for an account
400 * @param account ownCloud account.
402 public void cancel(Account account
) {
403 Log_OC
.d(TAG
, "Account= " + account
.name
);
405 if (mCurrentUpload
!= null
) {
406 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
407 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
408 mCurrentUpload
.cancel();
411 // Cancel pending uploads
412 cancelUploadsForAccount(account
);
415 public void clearListeners() {
416 mBoundListeners
.clear();
421 * Returns True when the file described by 'file' is being uploaded to
422 * the ownCloud account 'account' or waiting for it
424 * If 'file' is a directory, returns 'true' if some of its descendant files
425 * is uploading or waiting to upload.
427 * @param account ownCloud account where the remote file will be stored.
428 * @param file A file that could be in the queue of pending uploads
430 public boolean isUploading(Account account
, OCFile file
) {
431 if (account
== null
|| file
== null
) return false
;
432 return (mPendingUploads
.contains(account
, file
.getRemotePath()));
437 * Adds a listener interested in the progress of the upload for a concrete file.
439 * @param listener Object to notify about progress of transfer.
440 * @param account ownCloud account holding the file of interest.
441 * @param file {@link OCFile} of interest for listener.
443 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
,
444 Account account
, OCFile file
) {
445 if (account
== null
|| file
== null
|| listener
== null
) return;
446 String targetKey
= buildRemoteName(account
, file
);
447 mBoundListeners
.put(targetKey
, listener
);
453 * Removes a listener interested in the progress of the upload for a concrete file.
455 * @param listener Object to notify about progress of transfer.
456 * @param account ownCloud account holding the file of interest.
457 * @param file {@link OCFile} of interest for listener.
459 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
,
460 Account account
, OCFile file
) {
461 if (account
== null
|| file
== null
|| listener
== null
) return;
462 String targetKey
= buildRemoteName(account
, file
);
463 if (mBoundListeners
.get(targetKey
) == listener
) {
464 mBoundListeners
.remove(targetKey
);
470 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
471 long totalToTransfer
, String fileName
) {
472 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
473 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
474 if (boundListener
!= null
) {
475 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
,
476 totalToTransfer
, fileName
);
481 * Builds a key for the map of listeners.
483 * TODO remove and replace key with file.getFileId() after changing current policy (upload file, then
484 * add to local database) to better policy (add to local database, then upload)
486 * @param account ownCloud account where the file to upload belongs.
487 * @param file File to upload
490 private String
buildRemoteName(Account account
, OCFile file
) {
491 return account
.name
+ file
.getRemotePath();
497 * Upload worker. Performs the pending uploads in the order they were
500 * Created with the Looper of a new thread, started in
501 * {@link FileUploader#onCreate()}.
503 private static class ServiceHandler
extends Handler
{
504 // don't make it a final class, and don't remove the static ; lint will
505 // warn about a possible memory leak
506 FileUploader mService
;
508 public ServiceHandler(Looper looper
, FileUploader service
) {
511 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
516 public void handleMessage(Message msg
) {
517 @SuppressWarnings("unchecked")
518 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
519 if (msg
.obj
!= null
) {
520 Iterator
<String
> it
= requestedUploads
.iterator();
521 while (it
.hasNext()) {
522 mService
.uploadFile(it
.next());
525 Log_OC
.d(TAG
, "Stopping command after id " + msg
.arg1
);
526 mService
.stopSelf(msg
.arg1
);
531 * Core upload method: sends the file(s) to upload
533 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
535 public void uploadFile(String uploadKey
) {
537 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
539 if (mCurrentUpload
!= null
) {
540 // Detect if the account exists
541 if (AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
542 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().name
+ " exists");
544 notifyUploadStart(mCurrentUpload
);
546 RemoteOperationResult uploadResult
= null
, grantResult
;
549 /// prepare client object to send the request to the ownCloud server
550 if (mCurrentAccount
== null
|| !mCurrentAccount
.equals(mCurrentUpload
.getAccount())) {
551 mCurrentAccount
= mCurrentUpload
.getAccount();
552 mStorageManager
= new FileDataStorageManager(
556 } // else, reuse storage manager from previous operation
558 // always get client from client manager, to get fresh credentials in case of update
559 OwnCloudAccount ocAccount
= new OwnCloudAccount(mCurrentAccount
, this);
560 mUploadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
561 getClientFor(ocAccount
, this);
564 /// check the existence of the parent folder for the file to upload
565 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
566 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
567 remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
568 grantResult
= grantFolderExistence(remoteParentPath
);
570 /// perform the upload
571 if (grantResult
.isSuccess()) {
572 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
573 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
574 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
575 if (uploadResult
.isSuccess()) {
578 } else if (uploadResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
579 mStorageManager
.saveConflict(mCurrentUpload
.getFile(),
580 mCurrentUpload
.getFile().getEtagInConflict());
583 uploadResult
= grantResult
;
586 } catch (Exception e
) {
587 Log_OC
.e(TAG
, "Error uploading", e
);
588 uploadResult
= new RemoteOperationResult(e
);
591 Pair
<UploadFileOperation
, String
> removeResult
;
592 if (mCurrentUpload
.wasRenamed()) {
593 removeResult
= mPendingUploads
.removePayload(
595 mCurrentUpload
.getOldFile().getRemotePath()
598 removeResult
= mPendingUploads
.removePayload(
600 mCurrentUpload
.getRemotePath()
605 notifyUploadResult(mCurrentUpload
, uploadResult
);
607 sendBroadcastUploadFinished(mCurrentUpload
, uploadResult
, removeResult
.second
);
611 // Cancel the transfer
612 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().toString() +
614 cancelUploadsForAccount(mCurrentUpload
.getAccount());
622 * Checks the existence of the folder where the current file will be uploaded both
623 * in the remote server and in the local database.
625 * If the upload is set to enforce the creation of the folder, the method tries to
626 * create it both remote and locally.
628 * @param pathToGrant Full remote path whose existence will be granted.
629 * @return An {@link OCFile} instance corresponding to the folder where the file
632 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
633 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
634 RemoteOperationResult result
= operation
.execute(mUploadClient
);
635 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&&
636 mCurrentUpload
.isRemoteFolderToBeCreated()) {
637 SyncOperation syncOp
= new CreateFolderOperation( pathToGrant
, true
);
638 result
= syncOp
.execute(mUploadClient
, mStorageManager
);
640 if (result
.isSuccess()) {
641 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
642 if (parentDir
== null
) {
643 parentDir
= createLocalFolder(pathToGrant
);
645 if (parentDir
!= null
) {
646 result
= new RemoteOperationResult(ResultCode
.OK
);
648 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
655 private OCFile
createLocalFolder(String remotePath
) {
656 String parentPath
= new File(remotePath
).getParent();
657 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
658 parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
659 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
660 if (parent
== null
) {
661 parent
= createLocalFolder(parentPath
);
663 if (parent
!= null
) {
664 OCFile createdFolder
= new OCFile(remotePath
);
665 createdFolder
.setMimetype("DIR");
666 createdFolder
.setParentId(parent
.getFileId());
667 mStorageManager
.saveFile(createdFolder
);
668 return createdFolder
;
675 * Saves a OC File after a successful upload.
677 * A PROPFIND is necessary to keep the props in the local database
678 * synchronized with the server, specially the modification time and Etag
681 * TODO move into UploadFileOperation
683 private void saveUploadedFile() {
684 OCFile file
= mCurrentUpload
.getFile();
685 if (file
.fileExists()) {
686 file
= mStorageManager
.getFileById(file
.getFileId());
688 long syncDate
= System
.currentTimeMillis();
689 file
.setLastSyncDateForData(syncDate
);
691 // new PROPFIND to keep data consistent with server
692 // in theory, should return the same we already have
693 ReadRemoteFileOperation operation
=
694 new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
695 RemoteOperationResult result
= operation
.execute(mUploadClient
);
696 if (result
.isSuccess()) {
697 updateOCFile(file
, (RemoteFile
) result
.getData().get(0));
698 file
.setLastSyncDateForProperties(syncDate
);
700 Log_OC
.e(TAG
, "Error reading properties of file after successful upload; this is gonna hurt...");
703 // / maybe this would be better as part of UploadFileOperation... or
704 // maybe all this method
705 if (mCurrentUpload
.wasRenamed()) {
706 OCFile oldFile
= mCurrentUpload
.getOldFile();
707 if (oldFile
.fileExists()) {
708 oldFile
.setStoragePath(null
);
709 mStorageManager
.saveFile(oldFile
);
710 mStorageManager
.saveConflict(oldFile
, null
);
712 } // else: it was just an automatic renaming due to a name
713 // coincidence; nothing else is needed, the storagePath is right
714 // in the instance returned by mCurrentUpload.getFile()
716 file
.setNeedsUpdateThumbnail(true
);
717 mStorageManager
.saveFile(file
);
718 mStorageManager
.saveConflict(file
, null
);
720 mStorageManager
.triggerMediaScan(file
.getStoragePath());
724 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
725 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
726 file
.setFileLength(remoteFile
.getLength());
727 file
.setMimetype(remoteFile
.getMimeType());
728 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
729 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
730 file
.setEtag(remoteFile
.getEtag());
731 file
.setRemoteId(remoteFile
.getRemoteId());
734 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
) {
737 if (mimeType
== null
|| mimeType
.length() <= 0) {
739 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
740 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
741 } catch (IndexOutOfBoundsException e
) {
742 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " +
746 if (mimeType
== null
) {
747 mimeType
= "application/octet-stream";
750 if (isPdfFileFromContentProviderWithoutExtension(localPath
, mimeType
)){
751 remotePath
+= FILE_EXTENSION_PDF
;
754 OCFile newFile
= new OCFile(remotePath
);
755 newFile
.setStoragePath(localPath
);
756 newFile
.setLastSyncDateForProperties(0);
757 newFile
.setLastSyncDateForData(0);
760 if (localPath
!= null
&& localPath
.length() > 0) {
761 File localFile
= new File(localPath
);
762 newFile
.setFileLength(localFile
.length());
763 newFile
.setLastSyncDateForData(localFile
.lastModified());
764 } // don't worry about not assigning size, the problems with localPath
765 // are checked when the UploadFileOperation instance is created
768 newFile
.setMimetype(mimeType
);
774 * Creates a status notification to show the upload progress
776 * @param upload Upload operation starting.
778 private void notifyUploadStart(UploadFileOperation upload
) {
779 // / create status notification with a progress bar
781 mNotificationBuilder
=
782 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
785 .setSmallIcon(R
.drawable
.notification_icon
)
786 .setTicker(getString(R
.string
.uploader_upload_in_progress_ticker
))
787 .setContentTitle(getString(R
.string
.uploader_upload_in_progress_ticker
))
788 .setProgress(100, 0, false
)
790 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
792 /// includes a pending intent in the notification showing the details view of the file
793 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
794 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
795 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
796 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
797 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
798 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
801 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
805 * Callback method to update the progress bar in the status notification
808 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
809 long totalToTransfer
, String filePath
) {
810 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
811 if (percent
!= mLastPercent
) {
812 mNotificationBuilder
.setProgress(100, percent
, false
);
813 String fileName
= filePath
.substring(
814 filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
815 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
816 mNotificationBuilder
.setContentText(text
);
817 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
819 mLastPercent
= percent
;
823 * Updates the status notification with the result of an upload operation.
825 * @param uploadResult Result of the upload operation.
826 * @param upload Finished upload operation
828 private void notifyUploadResult(UploadFileOperation upload
,
829 RemoteOperationResult uploadResult
) {
830 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
831 // / cancelled operation or success -> silent removal of progress notification
832 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
834 // Show the result: success or fail notification
835 if (!uploadResult
.isCancelled()) {
836 int tickerId
= (uploadResult
.isSuccess()) ? R
.string
.uploader_upload_succeeded_ticker
:
837 R
.string
.uploader_upload_failed_ticker
;
841 // check credentials error
842 boolean needsToUpdateCredentials
= (
843 uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
844 uploadResult
.isIdPRedirection()
846 tickerId
= (needsToUpdateCredentials
) ?
847 R
.string
.uploader_upload_failed_credentials_error
: tickerId
;
850 .setTicker(getString(tickerId
))
851 .setContentTitle(getString(tickerId
))
854 .setProgress(0, 0, false
);
856 content
= ErrorMessageAdapter
.getErrorCauseMessage(
857 uploadResult
, upload
, getResources()
860 if (needsToUpdateCredentials
) {
861 // let the user update credentials with one click
862 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
863 updateAccountCredentials
.putExtra(
864 AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount()
866 updateAccountCredentials
.putExtra(
867 AuthenticatorActivity
.EXTRA_ACTION
,
868 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
870 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
871 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
872 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
873 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
875 (int) System
.currentTimeMillis(),
876 updateAccountCredentials
,
877 PendingIntent
.FLAG_ONE_SHOT
880 mUploadClient
= null
;
881 // grant that future retries on the same account will get the fresh credentials
883 mNotificationBuilder
.setContentText(content
);
885 if (upload
.isInstant()) {
888 db
= new DbHandler(this.getBaseContext());
889 String message
= uploadResult
.getLogMessage() + " errorCode: " +
890 uploadResult
.getCode();
891 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
892 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
893 //message = getString(R.string.failed_upload_quota_exceeded_text);
894 if (db
.updateFileState(
895 upload
.getOriginalStoragePath(),
896 DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
899 upload
.getOriginalStoragePath(),
900 upload
.getAccount().name
,
913 mNotificationBuilder
.setContentText(content
);
914 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
916 if (uploadResult
.isSuccess()) {
918 DbHandler db
= new DbHandler(this.getBaseContext());
919 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
922 // remove success notification, with a delay of 2 seconds
923 NotificationDelayer
.cancelWithDelay(
924 mNotificationManager
,
925 R
.string
.uploader_upload_succeeded_ticker
,
933 * Sends a broadcast in order to the interested activities can update their
936 * @param upload Finished upload operation
937 * @param uploadResult Result of the upload operation
938 * @param unlinkedFromRemotePath Path in the uploads tree where the upload was unlinked from
940 private void sendBroadcastUploadFinished(
941 UploadFileOperation upload
,
942 RemoteOperationResult uploadResult
,
943 String unlinkedFromRemotePath
) {
945 Intent end
= new Intent(getUploadFinishMessage());
946 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
951 if (upload
.wasRenamed()) {
952 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
954 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
955 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
956 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
957 if (unlinkedFromRemotePath
!= null
) {
958 end
.putExtra(EXTRA_LINKED_TO_PATH
, unlinkedFromRemotePath
);
961 sendStickyBroadcast(end
);
965 * Checks if content provider, using the content:// scheme, returns a file with mime-type
966 * 'application/pdf' but file has not extension
967 * @param localPath Full path to a file in the local file system.
968 * @param mimeType MIME type of the file.
969 * @return true if is needed to add the pdf file extension to the file
971 * TODO - move to OCFile or Utils class
973 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath
,
975 return localPath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
) &&
976 mimeType
.equals(MIME_TYPE_PDF
) &&
977 !localPath
.endsWith(FILE_EXTENSION_PDF
);
981 * Remove uploads of an account
983 * @param account Downloads account to remove
985 private void cancelUploadsForAccount(Account account
){
986 // Cancel pending uploads
987 mPendingUploads
.remove(account
);