1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 package com
.owncloud
.android
.files
.services
;
23 import java
.util
.AbstractList
;
24 import java
.util
.Iterator
;
25 import java
.util
.Vector
;
26 import java
.util
.concurrent
.ConcurrentHashMap
;
27 import java
.util
.concurrent
.ConcurrentMap
;
29 import org
.apache
.http
.HttpStatus
;
30 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
31 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
33 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
34 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
35 import com
.owncloud
.android
.datamodel
.OCFile
;
36 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
37 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
38 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
39 import com
.owncloud
.android
.operations
.UploadFileOperation
;
40 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
41 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
42 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
43 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
45 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
46 import eu
.alefzero
.webdav
.WebdavEntry
;
47 import eu
.alefzero
.webdav
.WebdavUtils
;
49 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
51 import android
.accounts
.Account
;
52 import android
.accounts
.AccountManager
;
53 import android
.app
.Notification
;
54 import android
.app
.NotificationManager
;
55 import android
.app
.PendingIntent
;
56 import android
.app
.Service
;
57 import android
.content
.Intent
;
58 import android
.os
.Binder
;
59 import android
.os
.Handler
;
60 import android
.os
.HandlerThread
;
61 import android
.os
.IBinder
;
62 import android
.os
.Looper
;
63 import android
.os
.Message
;
64 import android
.os
.Process
;
65 import android
.util
.Log
;
66 import android
.webkit
.MimeTypeMap
;
67 import android
.widget
.RemoteViews
;
69 import com
.owncloud
.android
.R
;
70 import eu
.alefzero
.webdav
.WebdavClient
;
72 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
74 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
75 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
76 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
77 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
78 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
79 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
81 public static final String KEY_FILE
= "FILE";
82 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
83 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
84 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
86 public static final String KEY_ACCOUNT
= "ACCOUNT";
88 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
89 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
90 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
91 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
93 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
94 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
95 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
97 public static final int UPLOAD_SINGLE_FILE
= 0;
98 public static final int UPLOAD_MULTIPLE_FILES
= 1;
100 private static final String TAG
= FileUploader
.class.getSimpleName();
102 private Looper mServiceLooper
;
103 private ServiceHandler mServiceHandler
;
104 private IBinder mBinder
;
105 private WebdavClient mUploadClient
= null
;
106 private Account mLastAccount
= null
;
107 private FileDataStorageManager mStorageManager
;
109 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
110 private UploadFileOperation mCurrentUpload
= null
;
112 private NotificationManager mNotificationManager
;
113 private Notification mNotification
;
114 private int mLastPercent
;
115 private RemoteViews mDefaultNotificationContentView
;
119 * Builds a key for mPendingUploads from the account and file to upload
121 * @param account Account where the file to download is stored
122 * @param file File to download
124 private String
buildRemoteName(Account account
, OCFile file
) {
125 return account
.name
+ file
.getRemotePath();
128 private String
buildRemoteName(Account account
, String remotePath
) {
129 return account
.name
+ remotePath
;
134 * Checks if an ownCloud server version should support chunked uploads.
136 * @param version OwnCloud version instance corresponding to an ownCloud server.
137 * @return 'True' if the ownCloud server with version supports chunked uploads.
139 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
140 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
146 * Service initialization
149 public void onCreate() {
151 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
152 HandlerThread thread
= new HandlerThread("FileUploaderThread",
153 Process
.THREAD_PRIORITY_BACKGROUND
);
155 mServiceLooper
= thread
.getLooper();
156 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
157 mBinder
= new FileUploaderBinder();
162 * Entry point to add one or several files to the queue of uploads.
164 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
165 * although the caller activity goes away.
168 public int onStartCommand(Intent intent
, int flags
, int startId
) {
169 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
) || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
170 Log
.e(TAG
, "Not enough information provided in intent");
171 return Service
.START_NOT_STICKY
;
173 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
174 if (uploadType
== -1) {
175 Log
.e(TAG
, "Incorrect upload type provided");
176 return Service
.START_NOT_STICKY
;
178 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
180 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
181 OCFile
[] files
= null
;
182 if (uploadType
== UPLOAD_SINGLE_FILE
) {
184 if (intent
.hasExtra(KEY_FILE
)) {
185 files
= new OCFile
[] {intent
.getParcelableExtra(KEY_FILE
) };
188 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
189 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
190 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
193 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
195 if (intent
.hasExtra(KEY_FILE
)) {
196 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO will this casting work fine?
199 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
200 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
201 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
205 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
207 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
208 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
209 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
210 boolean fixed
= false
;
212 fixed
= checkAndFixInstantUploadDirectory(storageManager
); // MUST be done BEFORE calling obtainNewOCFileToUpload
215 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
216 Log
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
217 return Service
.START_NOT_STICKY
;
219 } else if (!intent
.hasExtra(KEY_FILE
)) {
220 if (localPaths
== null
) {
221 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
222 return Service
.START_NOT_STICKY
;
224 if (remotePaths
== null
) {
225 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
226 return Service
.START_NOT_STICKY
;
228 if (localPaths
.length
!= remotePaths
.length
) {
229 Log
.e(TAG
, "Different number of remote paths and local paths!");
230 return Service
.START_NOT_STICKY
;
233 files
= new OCFile
[localPaths
.length
];
234 for (int i
=0; i
< localPaths
.length
; i
++) {
235 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!=null
)?mimeTypes
[i
]:(String
)null
), storageManager
);
239 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
240 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
241 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
242 String uploadKey
= null
;
243 UploadFileOperation newUpload
= null
;
245 for (int i
=0; i
< files
.length
; i
++) {
246 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
248 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
250 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
253 newUpload
.setRemoteFolderToBeCreated();
255 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
256 newUpload
.addDatatransferProgressListener(this);
257 requestedUploads
.add(uploadKey
);
260 } catch (IllegalArgumentException e
) {
261 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
262 return START_NOT_STICKY
;
264 } catch (IllegalStateException e
) {
265 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
266 return START_NOT_STICKY
;
268 } catch (Exception e
) {
269 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
270 return START_NOT_STICKY
;
274 if (requestedUploads
.size() > 0) {
275 Message msg
= mServiceHandler
.obtainMessage();
277 msg
.obj
= requestedUploads
;
278 mServiceHandler
.sendMessage(msg
);
281 return Service
.START_NOT_STICKY
;
286 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
288 * Implemented to perform cancellation, pause and resume of existing uploads.
291 public IBinder
onBind(Intent arg0
) {
296 * Binder to let client components to perform operations on the queue of uploads.
298 * It provides by itself the available operations.
300 public class FileUploaderBinder
extends Binder
{
303 * Cancels a pending or current upload of a remote file.
305 * @param account Owncloud account where the remote file will be stored.
306 * @param file A file in the queue of pending uploads
308 public void cancel(Account account
, OCFile file
) {
309 UploadFileOperation upload
= null
;
310 synchronized (mPendingUploads
) {
311 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
313 if (upload
!= null
) {
320 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
322 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
324 * @param account Owncloud account where the remote file will be stored.
325 * @param file A file that could be in the queue of pending uploads
327 public boolean isUploading(Account account
, OCFile file
) {
328 if (account
== null
|| file
== null
) return false
;
329 String targetKey
= buildRemoteName(account
, file
);
330 synchronized (mPendingUploads
) {
331 if (file
.isDirectory()) {
332 // this can be slow if there are many downloads :(
333 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
334 boolean found
= false
;
335 while (it
.hasNext() && !found
) {
336 found
= it
.next().startsWith(targetKey
);
340 return (mPendingUploads
.containsKey(targetKey
));
350 * Upload worker. Performs the pending uploads in the order they were requested.
352 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
354 private static class ServiceHandler
extends Handler
{
355 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
356 FileUploader mService
;
357 public ServiceHandler(Looper looper
, FileUploader service
) {
360 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
365 public void handleMessage(Message msg
) {
366 @SuppressWarnings("unchecked")
367 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
368 if (msg
.obj
!= null
) {
369 Iterator
<String
> it
= requestedUploads
.iterator();
370 while (it
.hasNext()) {
371 mService
.uploadFile(it
.next());
374 mService
.stopSelf(msg
.arg1
);
382 * Core upload method: sends the file(s) to upload
384 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
386 public void uploadFile(String uploadKey
) {
388 synchronized(mPendingUploads
) {
389 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
392 if (mCurrentUpload
!= null
) {
394 notifyUploadStart(mCurrentUpload
);
397 /// prepare client object to send requests to the ownCloud server
398 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
399 mLastAccount
= mCurrentUpload
.getAccount();
400 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
401 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
404 /// create remote folder for instant uploads
405 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
406 mUploadClient
.createDirectory(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
); // ignoring result; fail could just mean that it already exists, but local database is not synchronized; the upload will be tried anyway
410 /// perform the upload
411 RemoteOperationResult uploadResult
= null
;
413 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
414 if (uploadResult
.isSuccess()) {
419 synchronized(mPendingUploads
) {
420 mPendingUploads
.remove(uploadKey
);
425 notifyUploadResult(uploadResult
, mCurrentUpload
);
427 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
434 * Saves a OC File after a successful upload.
436 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
437 * specially the modification time and Etag (where available)
439 * TODO refactor this ugly thing
441 private void saveUploadedFile() {
442 OCFile file
= mCurrentUpload
.getFile();
443 long syncDate
= System
.currentTimeMillis();
444 file
.setLastSyncDateForData(syncDate
);
446 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
447 PropFindMethod propfind
= null
;
448 RemoteOperationResult result
= null
;
450 propfind
= new PropFindMethod(mUploadClient
.getBaseUri() + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
451 int status
= mUploadClient
.executeMethod(propfind
);
452 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
454 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
455 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0],
456 mUploadClient
.getBaseUri().getPath());
457 updateOCFile(file
, we
);
458 file
.setLastSyncDateForProperties(syncDate
);
461 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
464 result
= new RemoteOperationResult(isMultiStatus
, status
);
465 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage());
467 } catch (Exception e
) {
468 result
= new RemoteOperationResult(e
);
469 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage(), e
);
472 if (propfind
!= null
)
473 propfind
.releaseConnection();
476 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
477 if (mCurrentUpload
.wasRenamed()) {
478 OCFile oldFile
= mCurrentUpload
.getOldFile();
479 if (oldFile
.fileExists()) {
480 oldFile
.setStoragePath(null
);
481 mStorageManager
.saveFile(oldFile
);
483 } // else: it was just an automatic renaming due to a name coincidence; nothing else is needed, the storagePath is right in the instance returned by mCurrentUpload.getFile()
486 mStorageManager
.saveFile(file
);
490 private void updateOCFile(OCFile file
, WebdavEntry we
) {
491 file
.setCreationTimestamp(we
.createTimestamp());
492 file
.setFileLength(we
.contentLength());
493 file
.setMimetype(we
.contentType());
494 file
.setModificationTimestamp(we
.modifiedTimestamp());
495 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
496 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
500 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
501 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
502 if (instantUploadDir
== null
) {
503 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
504 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
505 newDir
.setMimetype("DIR");
506 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
507 storageManager
.saveFile(newDir
);
514 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, FileDataStorageManager storageManager
) {
515 OCFile newFile
= new OCFile(remotePath
);
516 newFile
.setStoragePath(localPath
);
517 newFile
.setLastSyncDateForProperties(0);
518 newFile
.setLastSyncDateForData(0);
521 if (localPath
!= null
&& localPath
.length() > 0) {
522 File localFile
= new File(localPath
);
523 newFile
.setFileLength(localFile
.length());
524 newFile
.setLastSyncDateForData(localFile
.lastModified());
525 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
528 if (mimeType
== null
|| mimeType
.length() <= 0) {
530 mimeType
= MimeTypeMap
.getSingleton()
531 .getMimeTypeFromExtension(
532 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
533 } catch (IndexOutOfBoundsException e
) {
534 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
537 if (mimeType
== null
) {
538 mimeType
= "application/octet-stream";
540 newFile
.setMimetype(mimeType
);
543 String parentPath
= new File(remotePath
).getParent();
544 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
545 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
546 if (parentDir
== null
) {
547 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath
);
549 long parentDirId
= parentDir
.getFileId();
550 newFile
.setParentId(parentDirId
);
556 * Creates a status notification to show the upload progress
558 * @param upload Upload operation starting.
560 private void notifyUploadStart(UploadFileOperation upload
) {
561 /// create status notification with a progress bar
563 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
564 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
565 mDefaultNotificationContentView
= mNotification
.contentView
;
566 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
567 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
568 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, upload
.getFileName()));
569 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
571 /// includes a pending intent in the notification showing the details view of the file
572 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
573 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
574 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
575 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
576 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
578 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
583 * Callback method to update the progress bar in the status notification
586 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
587 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
588 if (percent
!= mLastPercent
) {
589 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
590 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
591 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
592 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
594 mLastPercent
= percent
;
599 * Callback method to update the progress bar in the status notification (old version)
602 public void onTransferProgress(long progressRate
) {
603 // NOTHING TO DO HERE ANYMORE
608 * Updates the status notification with the result of an upload operation.
610 * @param uploadResult Result of the upload operation.
611 * @param upload Finished upload operation
613 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
614 if (uploadResult
.isCancelled()) {
615 /// cancelled operation -> silent removal of progress notification
616 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
618 } else if (uploadResult
.isSuccess()) {
619 /// success -> silent update of progress notification to success message
620 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
621 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
622 mNotification
.contentView
= mDefaultNotificationContentView
;
624 /// includes a pending intent in the notification showing the details view of the file
625 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
626 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
627 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
628 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
629 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
631 mNotification
.setLatestEventInfo( getApplicationContext(),
632 getString(R
.string
.uploader_upload_succeeded_ticker
),
633 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), upload
.getFileName()),
634 mNotification
.contentIntent
);
636 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT AN ERROR; uploader_upload_in_progress_ticker is the target, not a new notification
638 /* Notification about multiple uploads: pending of update
639 mNotification.setLatestEventInfo( getApplicationContext(),
640 getString(R.string.uploader_upload_succeeded_ticker),
641 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
642 mNotification.contentIntent);
646 /// fail -> explicit failure notification
647 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
648 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
649 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
650 // TODO put something smart in the contentIntent below
651 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
653 String content
= null
;
654 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
||
655 uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
656 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
657 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), upload
.getFileName(), getString(R
.string
.app_name
));
659 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), upload
.getFileName());
661 finalNotification
.setLatestEventInfo( getApplicationContext(),
662 getString(R
.string
.uploader_upload_failed_ticker
),
664 finalNotification
.contentIntent
);
666 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
668 /* Notification about multiple uploads failure: pending of update
669 finalNotification.setLatestEventInfo( getApplicationContext(),
670 getString(R.string.uploader_upload_failed_ticker),
671 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
672 finalNotification.contentIntent);
680 * Sends a broadcast in order to the interested activities can update their view
682 * @param upload Finished upload operation
683 * @param uploadResult Result of the upload operation
685 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
686 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
687 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote path, after possible automatic renaming
688 if (upload
.wasRenamed()) {
689 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
691 end
.putExtra(EXTRA_OLD_FILE_PATH
, upload
.getOriginalStoragePath());
692 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
693 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
694 sendStickyBroadcast(end
);