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;
104 public static final int LOCAL_BEHAVIOUR_REMOVE
= 3;
106 public static final int UPLOAD_SINGLE_FILE
= 0;
107 public static final int UPLOAD_MULTIPLE_FILES
= 1;
109 private static final String TAG
= FileUploader
.class.getSimpleName();
111 private Looper mServiceLooper
;
112 private ServiceHandler mServiceHandler
;
113 private IBinder mBinder
;
114 private OwnCloudClient mUploadClient
= null
;
115 private Account mCurrentAccount
= null
;
116 private FileDataStorageManager mStorageManager
;
118 private IndexedForest
<UploadFileOperation
> mPendingUploads
= new IndexedForest
<UploadFileOperation
>();
119 private UploadFileOperation mCurrentUpload
= null
;
121 private NotificationManager mNotificationManager
;
122 private NotificationCompat
.Builder mNotificationBuilder
;
123 private int mLastPercent
;
125 private static final String MIME_TYPE_PDF
= "application/pdf";
126 private static final String FILE_EXTENSION_PDF
= ".pdf";
129 public static String
getUploadFinishMessage() {
130 return FileUploader
.class.getName() + UPLOAD_FINISH_MESSAGE
;
134 * Checks if an ownCloud server version should support chunked uploads.
136 * @param version OwnCloud version instance corresponding to an ownCloud
138 * @return 'True' if the ownCloud server with version supports chunked
141 * TODO - move to OCClient
143 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
144 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
148 * Service initialization
151 public void onCreate() {
153 Log_OC
.d(TAG
, "Creating service");
154 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
155 HandlerThread thread
= new HandlerThread("FileUploaderThread",
156 Process
.THREAD_PRIORITY_BACKGROUND
);
158 mServiceLooper
= thread
.getLooper();
159 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
160 mBinder
= new FileUploaderBinder();
162 // add AccountsUpdatedListener
163 AccountManager am
= AccountManager
.get(getApplicationContext());
164 am
.addOnAccountsUpdatedListener(this, null
, false
);
171 public void onDestroy() {
172 Log_OC
.v(TAG
, "Destroying service" );
174 mServiceHandler
= null
;
175 mServiceLooper
.quit();
176 mServiceLooper
= null
;
177 mNotificationManager
= null
;
179 // remove AccountsUpdatedListener
180 AccountManager am
= AccountManager
.get(getApplicationContext());
181 am
.removeOnAccountsUpdatedListener(this);
188 * Entry point to add one or several files to the queue of uploads.
190 * New uploads are added calling to startService(), resulting in a call to
191 * this method. This ensures the service will keep on working although the
192 * caller activity goes away.
195 public int onStartCommand(Intent intent
, int flags
, int startId
) {
196 Log_OC
.d(TAG
, "Starting command with id " + startId
);
198 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
)
199 || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
200 Log_OC
.e(TAG
, "Not enough information provided in intent");
201 return Service
.START_NOT_STICKY
;
203 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
204 if (uploadType
== -1) {
205 Log_OC
.e(TAG
, "Incorrect upload type provided");
206 return Service
.START_NOT_STICKY
;
208 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
209 if (!AccountUtils
.exists(account
, getApplicationContext())) {
210 return Service
.START_NOT_STICKY
;
213 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
214 OCFile
[] files
= null
;
215 if (uploadType
== UPLOAD_SINGLE_FILE
) {
217 if (intent
.hasExtra(KEY_FILE
)) {
218 files
= new OCFile
[] { intent
.getParcelableExtra(KEY_FILE
) };
221 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
222 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
223 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
226 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
228 if (intent
.hasExtra(KEY_FILE
)) {
229 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO
237 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
238 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
239 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
243 FileDataStorageManager storageManager
= new FileDataStorageManager(account
,
244 getContentResolver());
246 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
247 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
248 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
250 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
251 Log_OC
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
252 return Service
.START_NOT_STICKY
;
254 } else if (!intent
.hasExtra(KEY_FILE
)) {
255 if (localPaths
== null
) {
256 Log_OC
.e(TAG
, "Incorrect array for local paths provided in upload intent");
257 return Service
.START_NOT_STICKY
;
259 if (remotePaths
== null
) {
260 Log_OC
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
261 return Service
.START_NOT_STICKY
;
263 if (localPaths
.length
!= remotePaths
.length
) {
264 Log_OC
.e(TAG
, "Different number of remote paths and local paths!");
265 return Service
.START_NOT_STICKY
;
268 files
= new OCFile
[localPaths
.length
];
269 for (int i
= 0; i
< localPaths
.length
; i
++) {
270 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
],
271 ((mimeTypes
!= null
) ? mimeTypes
[i
] : null
));
272 if (files
[i
] == null
) {
273 // TODO @andomaex add failure Notification
274 return Service
.START_NOT_STICKY
;
279 OwnCloudVersion ocv
= AccountUtils
.getServerVersion(account
);
281 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
282 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
283 String uploadKey
= null
;
284 UploadFileOperation newUpload
= null
;
286 for (int i
= 0; i
< files
.length
; i
++) {
287 newUpload
= new UploadFileOperation(
292 forceOverwrite
, localAction
,
293 getApplicationContext()
296 newUpload
.setRemoteFolderToBeCreated();
298 newUpload
.addDatatransferProgressListener(this);
299 newUpload
.addDatatransferProgressListener((FileUploaderBinder
) mBinder
);
300 Pair
<String
, String
> putResult
= mPendingUploads
.putIfAbsent(
301 account
, files
[i
].getRemotePath(), newUpload
303 uploadKey
= putResult
.first
;
304 requestedUploads
.add(uploadKey
);
307 } catch (IllegalArgumentException e
) {
308 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
309 return START_NOT_STICKY
;
311 } catch (IllegalStateException e
) {
312 Log_OC
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
313 return START_NOT_STICKY
;
315 } catch (Exception e
) {
316 Log_OC
.e(TAG
, "Unexpected exception while processing upload intent", e
);
317 return START_NOT_STICKY
;
321 if (requestedUploads
.size() > 0) {
322 Message msg
= mServiceHandler
.obtainMessage();
324 msg
.obj
= requestedUploads
;
325 mServiceHandler
.sendMessage(msg
);
327 return Service
.START_NOT_STICKY
;
331 * Provides a binder object that clients can use to perform operations on
332 * the queue of uploads, excepting the addition of new files.
334 * Implemented to perform cancellation, pause and resume of existing
338 public IBinder
onBind(Intent arg0
) {
343 * Called when ALL the bound clients were onbound.
346 public boolean onUnbind(Intent intent
) {
347 ((FileUploaderBinder
)mBinder
).clearListeners();
348 return false
; // not accepting rebinding (default behaviour)
352 public void onAccountsUpdated(Account
[] accounts
) {
353 // Review current upload, and cancel it if its account doen't exist
354 if (mCurrentUpload
!= null
&&
355 !AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
356 mCurrentUpload
.cancel();
358 // The rest of uploads are cancelled when they try to start
362 * Binder to let client components to perform operations on the queue of
365 * It provides by itself the available operations.
367 public class FileUploaderBinder
extends Binder
implements OnDatatransferProgressListener
{
370 * Map of listeners that will be reported about progress of uploads from a
371 * {@link FileUploaderBinder} instance
373 private Map
<String
, OnDatatransferProgressListener
> mBoundListeners
=
374 new HashMap
<String
, OnDatatransferProgressListener
>();
377 * Cancels a pending or current upload of a remote file.
379 * @param account ownCloud account where the remote file will be stored.
380 * @param file A file in the queue of pending uploads
382 public void cancel(Account account
, OCFile file
) {
383 Pair
<UploadFileOperation
, String
> removeResult
= mPendingUploads
.remove(account
, file
.getRemotePath());
384 UploadFileOperation upload
= removeResult
.first
;
385 if (upload
!= null
) {
388 if (mCurrentUpload
!= null
&& mCurrentAccount
!= null
&&
389 mCurrentUpload
.getRemotePath().startsWith(file
.getRemotePath()) &&
390 account
.name
.equals(mCurrentAccount
.name
)) {
391 mCurrentUpload
.cancel();
397 * Cancels all the uploads for an account
399 * @param account ownCloud account.
401 public void cancel(Account account
) {
402 Log_OC
.d(TAG
, "Account= " + account
.name
);
404 if (mCurrentUpload
!= null
) {
405 Log_OC
.d(TAG
, "Current Upload Account= " + mCurrentUpload
.getAccount().name
);
406 if (mCurrentUpload
.getAccount().name
.equals(account
.name
)) {
407 mCurrentUpload
.cancel();
410 // Cancel pending uploads
411 cancelUploadsForAccount(account
);
414 public void clearListeners() {
415 mBoundListeners
.clear();
420 * Returns True when the file described by 'file' is being uploaded to
421 * the ownCloud account 'account' or waiting for it
423 * If 'file' is a directory, returns 'true' if some of its descendant files
424 * is uploading or waiting to upload.
426 * @param account ownCloud account where the remote file will be stored.
427 * @param file A file that could be in the queue of pending uploads
429 public boolean isUploading(Account account
, OCFile file
) {
430 if (account
== null
|| file
== null
) return false
;
431 return (mPendingUploads
.contains(account
, file
.getRemotePath()));
436 * Adds a listener interested in the progress of the upload for a concrete file.
438 * @param listener Object to notify about progress of transfer.
439 * @param account ownCloud account holding the file of interest.
440 * @param file {@link OCFile} of interest for listener.
442 public void addDatatransferProgressListener (OnDatatransferProgressListener listener
,
443 Account account
, OCFile file
) {
444 if (account
== null
|| file
== null
|| listener
== null
) return;
445 String targetKey
= buildRemoteName(account
, file
);
446 mBoundListeners
.put(targetKey
, listener
);
452 * Removes a listener interested in the progress of the upload for a concrete file.
454 * @param listener Object to notify about progress of transfer.
455 * @param account ownCloud account holding the file of interest.
456 * @param file {@link OCFile} of interest for listener.
458 public void removeDatatransferProgressListener (OnDatatransferProgressListener listener
,
459 Account account
, OCFile file
) {
460 if (account
== null
|| file
== null
|| listener
== null
) return;
461 String targetKey
= buildRemoteName(account
, file
);
462 if (mBoundListeners
.get(targetKey
) == listener
) {
463 mBoundListeners
.remove(targetKey
);
469 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
470 long totalToTransfer
, String fileName
) {
471 String key
= buildRemoteName(mCurrentUpload
.getAccount(), mCurrentUpload
.getFile());
472 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(key
);
473 if (boundListener
!= null
) {
474 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
,
475 totalToTransfer
, fileName
);
480 * Builds a key for the map of listeners.
482 * TODO remove and replace key with file.getFileId() after changing current policy (upload file, then
483 * add to local database) to better policy (add to local database, then upload)
485 * @param account ownCloud account where the file to upload belongs.
486 * @param file File to upload
489 private String
buildRemoteName(Account account
, OCFile file
) {
490 return account
.name
+ file
.getRemotePath();
496 * Upload worker. Performs the pending uploads in the order they were
499 * Created with the Looper of a new thread, started in
500 * {@link FileUploader#onCreate()}.
502 private static class ServiceHandler
extends Handler
{
503 // don't make it a final class, and don't remove the static ; lint will
504 // warn about a possible memory leak
505 FileUploader mService
;
507 public ServiceHandler(Looper looper
, FileUploader service
) {
510 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
515 public void handleMessage(Message msg
) {
516 @SuppressWarnings("unchecked")
517 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
518 if (msg
.obj
!= null
) {
519 Iterator
<String
> it
= requestedUploads
.iterator();
520 while (it
.hasNext()) {
521 mService
.uploadFile(it
.next());
524 Log_OC
.d(TAG
, "Stopping command after id " + msg
.arg1
);
525 mService
.stopSelf(msg
.arg1
);
530 * Core upload method: sends the file(s) to upload
532 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
534 public void uploadFile(String uploadKey
) {
536 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
538 if (mCurrentUpload
!= null
) {
539 // Detect if the account exists
540 if (AccountUtils
.exists(mCurrentUpload
.getAccount(), getApplicationContext())) {
541 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().name
+ " exists");
543 notifyUploadStart(mCurrentUpload
);
545 RemoteOperationResult uploadResult
= null
, grantResult
;
548 /// prepare client object to send the request to the ownCloud server
549 if (mCurrentAccount
== null
|| !mCurrentAccount
.equals(mCurrentUpload
.getAccount())) {
550 mCurrentAccount
= mCurrentUpload
.getAccount();
551 mStorageManager
= new FileDataStorageManager(
555 } // else, reuse storage manager from previous operation
557 // always get client from client manager, to get fresh credentials in case of update
558 OwnCloudAccount ocAccount
= new OwnCloudAccount(mCurrentAccount
, this);
559 mUploadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
560 getClientFor(ocAccount
, this);
563 /// check the existence of the parent folder for the file to upload
564 String remoteParentPath
= new File(mCurrentUpload
.getRemotePath()).getParent();
565 remoteParentPath
= remoteParentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
566 remoteParentPath
: remoteParentPath
+ OCFile
.PATH_SEPARATOR
;
567 grantResult
= grantFolderExistence(remoteParentPath
);
569 /// perform the upload
570 if (grantResult
.isSuccess()) {
571 OCFile parent
= mStorageManager
.getFileByPath(remoteParentPath
);
572 mCurrentUpload
.getFile().setParentId(parent
.getFileId());
573 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
574 if (uploadResult
.isSuccess()) {
577 } else if (uploadResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
578 mStorageManager
.saveConflict(mCurrentUpload
.getFile(),
579 mCurrentUpload
.getFile().getEtagInConflict());
582 uploadResult
= grantResult
;
585 } catch (Exception e
) {
586 Log_OC
.e(TAG
, "Error uploading", e
);
587 uploadResult
= new RemoteOperationResult(e
);
590 Pair
<UploadFileOperation
, String
> removeResult
;
591 if (mCurrentUpload
.wasRenamed()) {
592 removeResult
= mPendingUploads
.removePayload(
594 mCurrentUpload
.getOldFile().getRemotePath()
597 removeResult
= mPendingUploads
.removePayload(
599 mCurrentUpload
.getRemotePath()
604 notifyUploadResult(mCurrentUpload
, uploadResult
);
606 sendBroadcastUploadFinished(mCurrentUpload
, uploadResult
, removeResult
.second
);
610 // Cancel the transfer
611 Log_OC
.d(TAG
, "Account " + mCurrentUpload
.getAccount().toString() +
613 cancelUploadsForAccount(mCurrentUpload
.getAccount());
621 * Checks the existence of the folder where the current file will be uploaded both
622 * in the remote server and in the local database.
624 * If the upload is set to enforce the creation of the folder, the method tries to
625 * create it both remote and locally.
627 * @param pathToGrant Full remote path whose existence will be granted.
628 * @return An {@link OCFile} instance corresponding to the folder where the file
631 private RemoteOperationResult
grantFolderExistence(String pathToGrant
) {
632 RemoteOperation operation
= new ExistenceCheckRemoteOperation(pathToGrant
, this, false
);
633 RemoteOperationResult result
= operation
.execute(mUploadClient
);
634 if (!result
.isSuccess() && result
.getCode() == ResultCode
.FILE_NOT_FOUND
&&
635 mCurrentUpload
.isRemoteFolderToBeCreated()) {
636 SyncOperation syncOp
= new CreateFolderOperation( pathToGrant
, true
);
637 result
= syncOp
.execute(mUploadClient
, mStorageManager
);
639 if (result
.isSuccess()) {
640 OCFile parentDir
= mStorageManager
.getFileByPath(pathToGrant
);
641 if (parentDir
== null
) {
642 parentDir
= createLocalFolder(pathToGrant
);
644 if (parentDir
!= null
) {
645 result
= new RemoteOperationResult(ResultCode
.OK
);
647 result
= new RemoteOperationResult(ResultCode
.UNKNOWN_ERROR
);
654 private OCFile
createLocalFolder(String remotePath
) {
655 String parentPath
= new File(remotePath
).getParent();
656 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ?
657 parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
658 OCFile parent
= mStorageManager
.getFileByPath(parentPath
);
659 if (parent
== null
) {
660 parent
= createLocalFolder(parentPath
);
662 if (parent
!= null
) {
663 OCFile createdFolder
= new OCFile(remotePath
);
664 createdFolder
.setMimetype("DIR");
665 createdFolder
.setParentId(parent
.getFileId());
666 mStorageManager
.saveFile(createdFolder
);
667 return createdFolder
;
674 * Saves a OC File after a successful upload.
676 * A PROPFIND is necessary to keep the props in the local database
677 * synchronized with the server, specially the modification time and Etag
680 * TODO move into UploadFileOperation
682 private void saveUploadedFile() {
683 OCFile file
= mCurrentUpload
.getFile();
684 if (file
.fileExists()) {
685 file
= mStorageManager
.getFileById(file
.getFileId());
687 long syncDate
= System
.currentTimeMillis();
688 file
.setLastSyncDateForData(syncDate
);
690 // new PROPFIND to keep data consistent with server
691 // in theory, should return the same we already have
692 ReadRemoteFileOperation operation
=
693 new ReadRemoteFileOperation(mCurrentUpload
.getRemotePath());
694 RemoteOperationResult result
= operation
.execute(mUploadClient
);
695 if (result
.isSuccess()) {
696 updateOCFile(file
, (RemoteFile
) result
.getData().get(0));
697 file
.setLastSyncDateForProperties(syncDate
);
699 Log_OC
.e(TAG
, "Error reading properties of file after successful upload; this is gonna hurt...");
702 // / maybe this would be better as part of UploadFileOperation... or
703 // maybe all this method
704 if (mCurrentUpload
.wasRenamed()) {
705 OCFile oldFile
= mCurrentUpload
.getOldFile();
706 if (oldFile
.fileExists()) {
707 oldFile
.setStoragePath(null
);
708 mStorageManager
.saveFile(oldFile
);
709 mStorageManager
.saveConflict(oldFile
, null
);
711 } // else: it was just an automatic renaming due to a name
712 // coincidence; nothing else is needed, the storagePath is right
713 // in the instance returned by mCurrentUpload.getFile()
715 file
.setNeedsUpdateThumbnail(true
);
716 mStorageManager
.saveFile(file
);
717 mStorageManager
.saveConflict(file
, null
);
719 mStorageManager
.triggerMediaScan(file
.getStoragePath());
723 private void updateOCFile(OCFile file
, RemoteFile remoteFile
) {
724 file
.setCreationTimestamp(remoteFile
.getCreationTimestamp());
725 file
.setFileLength(remoteFile
.getLength());
726 file
.setMimetype(remoteFile
.getMimeType());
727 file
.setModificationTimestamp(remoteFile
.getModifiedTimestamp());
728 file
.setModificationTimestampAtLastSyncForData(remoteFile
.getModifiedTimestamp());
729 file
.setEtag(remoteFile
.getEtag());
730 file
.setRemoteId(remoteFile
.getRemoteId());
733 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
) {
736 if (mimeType
== null
|| mimeType
.length() <= 0) {
738 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(
739 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
740 } catch (IndexOutOfBoundsException e
) {
741 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " +
745 if (mimeType
== null
) {
746 mimeType
= "application/octet-stream";
749 if (isPdfFileFromContentProviderWithoutExtension(localPath
, mimeType
)){
750 remotePath
+= FILE_EXTENSION_PDF
;
753 OCFile newFile
= new OCFile(remotePath
);
754 newFile
.setStoragePath(localPath
);
755 newFile
.setLastSyncDateForProperties(0);
756 newFile
.setLastSyncDateForData(0);
759 if (localPath
!= null
&& localPath
.length() > 0) {
760 File localFile
= new File(localPath
);
761 newFile
.setFileLength(localFile
.length());
762 newFile
.setLastSyncDateForData(localFile
.lastModified());
763 } // don't worry about not assigning size, the problems with localPath
764 // are checked when the UploadFileOperation instance is created
767 newFile
.setMimetype(mimeType
);
773 * Creates a status notification to show the upload progress
775 * @param upload Upload operation starting.
777 private void notifyUploadStart(UploadFileOperation upload
) {
778 // / create status notification with a progress bar
780 mNotificationBuilder
=
781 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
784 .setSmallIcon(R
.drawable
.notification_icon
)
785 .setTicker(getString(R
.string
.uploader_upload_in_progress_ticker
))
786 .setContentTitle(getString(R
.string
.uploader_upload_in_progress_ticker
))
787 .setProgress(100, 0, false
)
789 String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
791 /// includes a pending intent in the notification showing the details view of the file
792 Intent showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
793 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, upload
.getFile());
794 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, upload
.getAccount());
795 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
796 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
797 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
800 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
804 * Callback method to update the progress bar in the status notification
807 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
,
808 long totalToTransfer
, String filePath
) {
809 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
810 if (percent
!= mLastPercent
) {
811 mNotificationBuilder
.setProgress(100, percent
, false
);
812 String fileName
= filePath
.substring(
813 filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
814 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
815 mNotificationBuilder
.setContentText(text
);
816 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotificationBuilder
.build());
818 mLastPercent
= percent
;
822 * Updates the status notification with the result of an upload operation.
824 * @param uploadResult Result of the upload operation.
825 * @param upload Finished upload operation
827 private void notifyUploadResult(UploadFileOperation upload
,
828 RemoteOperationResult uploadResult
) {
829 Log_OC
.d(TAG
, "NotifyUploadResult with resultCode: " + uploadResult
.getCode());
830 // / cancelled operation or success -> silent removal of progress notification
831 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
833 // Show the result: success or fail notification
834 if (!uploadResult
.isCancelled()) {
835 int tickerId
= (uploadResult
.isSuccess()) ? R
.string
.uploader_upload_succeeded_ticker
:
836 R
.string
.uploader_upload_failed_ticker
;
840 // check credentials error
841 boolean needsToUpdateCredentials
= (
842 uploadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
843 uploadResult
.isIdPRedirection()
845 tickerId
= (needsToUpdateCredentials
) ?
846 R
.string
.uploader_upload_failed_credentials_error
: tickerId
;
849 .setTicker(getString(tickerId
))
850 .setContentTitle(getString(tickerId
))
853 .setProgress(0, 0, false
);
855 content
= ErrorMessageAdapter
.getErrorCauseMessage(
856 uploadResult
, upload
, getResources()
859 if (needsToUpdateCredentials
) {
860 // let the user update credentials with one click
861 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
862 updateAccountCredentials
.putExtra(
863 AuthenticatorActivity
.EXTRA_ACCOUNT
, upload
.getAccount()
865 updateAccountCredentials
.putExtra(
866 AuthenticatorActivity
.EXTRA_ACTION
,
867 AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
869 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
870 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
871 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
872 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
874 (int) System
.currentTimeMillis(),
875 updateAccountCredentials
,
876 PendingIntent
.FLAG_ONE_SHOT
879 mUploadClient
= null
;
880 // grant that future retries on the same account will get the fresh credentials
882 mNotificationBuilder
.setContentText(content
);
884 if (upload
.isInstant()) {
887 db
= new DbHandler(this.getBaseContext());
888 String message
= uploadResult
.getLogMessage() + " errorCode: " +
889 uploadResult
.getCode();
890 Log_OC
.e(TAG
, message
+ " Http-Code: " + uploadResult
.getHttpCode());
891 if (uploadResult
.getCode() == ResultCode
.QUOTA_EXCEEDED
) {
892 //message = getString(R.string.failed_upload_quota_exceeded_text);
893 if (db
.updateFileState(
894 upload
.getOriginalStoragePath(),
895 DbHandler
.UPLOAD_STATUS_UPLOAD_FAILED
,
898 upload
.getOriginalStoragePath(),
899 upload
.getAccount().name
,
912 mNotificationBuilder
.setContentText(content
);
913 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
915 if (uploadResult
.isSuccess()) {
917 DbHandler db
= new DbHandler(this.getBaseContext());
918 db
.removeIUPendingFile(mCurrentUpload
.getOriginalStoragePath());
921 // remove success notification, with a delay of 2 seconds
922 NotificationDelayer
.cancelWithDelay(
923 mNotificationManager
,
924 R
.string
.uploader_upload_succeeded_ticker
,
932 * Sends a broadcast in order to the interested activities can update their
935 * @param upload Finished upload operation
936 * @param uploadResult Result of the upload operation
937 * @param unlinkedFromRemotePath Path in the uploads tree where the upload was unlinked from
939 private void sendBroadcastUploadFinished(
940 UploadFileOperation upload
,
941 RemoteOperationResult uploadResult
,
942 String unlinkedFromRemotePath
) {
944 Intent end
= new Intent(getUploadFinishMessage());
945 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote
950 if (upload
.wasRenamed()) {
951 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
953 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
954 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
955 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
956 if (unlinkedFromRemotePath
!= null
) {
957 end
.putExtra(EXTRA_LINKED_TO_PATH
, unlinkedFromRemotePath
);
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 * TODO - move to OCFile or Utils class
972 private boolean isPdfFileFromContentProviderWithoutExtension(String localPath
,
974 return localPath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
) &&
975 mimeType
.equals(MIME_TYPE_PDF
) &&
976 !localPath
.endsWith(FILE_EXTENSION_PDF
);
980 * Remove uploads of an account
982 * @param account Downloads account to remove
984 private void cancelUploadsForAccount(Account account
){
985 // Cancel pending uploads
986 mPendingUploads
.remove(account
);