1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.util
.AbstractList
;
23 import java
.util
.Iterator
;
24 import java
.util
.Vector
;
25 import java
.util
.concurrent
.ConcurrentHashMap
;
26 import java
.util
.concurrent
.ConcurrentMap
;
28 import org
.apache
.http
.HttpStatus
;
29 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
30 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
32 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
33 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
34 import com
.owncloud
.android
.datamodel
.OCFile
;
35 import com
.owncloud
.android
.files
.InstantUploadBroadcastReceiver
;
36 import com
.owncloud
.android
.operations
.ChunkedUploadFileOperation
;
37 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
38 import com
.owncloud
.android
.operations
.UploadFileOperation
;
39 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
40 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
41 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
42 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
44 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
45 import eu
.alefzero
.webdav
.WebdavEntry
;
46 import eu
.alefzero
.webdav
.WebdavUtils
;
48 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
50 import android
.accounts
.Account
;
51 import android
.accounts
.AccountManager
;
52 import android
.app
.Notification
;
53 import android
.app
.NotificationManager
;
54 import android
.app
.PendingIntent
;
55 import android
.app
.Service
;
56 import android
.content
.Intent
;
57 import android
.os
.Binder
;
58 import android
.os
.Handler
;
59 import android
.os
.HandlerThread
;
60 import android
.os
.IBinder
;
61 import android
.os
.Looper
;
62 import android
.os
.Message
;
63 import android
.os
.Process
;
64 import android
.util
.Log
;
65 import android
.webkit
.MimeTypeMap
;
66 import android
.widget
.RemoteViews
;
68 import com
.owncloud
.android
.R
;
69 import eu
.alefzero
.webdav
.WebdavClient
;
71 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
73 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
74 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
75 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
76 public static final String EXTRA_OLD_REMOTE_PATH
= "OLD_REMOTE_PATH";
77 public static final String EXTRA_OLD_FILE_PATH
= "OLD_FILE_PATH";
78 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
80 public static final String KEY_FILE
= "FILE";
81 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
82 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
83 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
85 public static final String KEY_ACCOUNT
= "ACCOUNT";
87 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
88 public static final String KEY_FORCE_OVERWRITE
= "KEY_FORCE_OVERWRITE";
89 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
90 public static final String KEY_LOCAL_BEHAVIOUR
= "BEHAVIOUR";
92 public static final int LOCAL_BEHAVIOUR_COPY
= 0;
93 public static final int LOCAL_BEHAVIOUR_MOVE
= 1;
94 public static final int LOCAL_BEHAVIOUR_FORGET
= 2;
96 public static final int UPLOAD_SINGLE_FILE
= 0;
97 public static final int UPLOAD_MULTIPLE_FILES
= 1;
99 private static final String TAG
= FileUploader
.class.getSimpleName();
101 private Looper mServiceLooper
;
102 private ServiceHandler mServiceHandler
;
103 private IBinder mBinder
;
104 private WebdavClient mUploadClient
= null
;
105 private Account mLastAccount
= null
;
106 private FileDataStorageManager mStorageManager
;
108 private ConcurrentMap
<String
, UploadFileOperation
> mPendingUploads
= new ConcurrentHashMap
<String
, UploadFileOperation
>();
109 private UploadFileOperation mCurrentUpload
= null
;
111 private NotificationManager mNotificationManager
;
112 private Notification mNotification
;
113 private int mLastPercent
;
114 private RemoteViews mDefaultNotificationContentView
;
118 * Builds a key for mPendingUploads from the account and file to upload
120 * @param account Account where the file to download is stored
121 * @param file File to download
123 private String
buildRemoteName(Account account
, OCFile file
) {
124 return account
.name
+ file
.getRemotePath();
127 private String
buildRemoteName(Account account
, String remotePath
) {
128 return account
.name
+ remotePath
;
133 * Checks if an ownCloud server version should support chunked uploads.
135 * @param version OwnCloud version instance corresponding to an ownCloud server.
136 * @return 'True' if the ownCloud server with version supports chunked uploads.
138 private static boolean chunkedUploadIsSupported(OwnCloudVersion version
) {
139 return (version
!= null
&& version
.compareTo(OwnCloudVersion
.owncloud_v4_5
) >= 0);
145 * Service initialization
148 public void onCreate() {
150 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
151 HandlerThread thread
= new HandlerThread("FileUploaderThread",
152 Process
.THREAD_PRIORITY_BACKGROUND
);
154 mServiceLooper
= thread
.getLooper();
155 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
156 mBinder
= new FileUploaderBinder();
161 * Entry point to add one or several files to the queue of uploads.
163 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
164 * although the caller activity goes away.
167 public int onStartCommand(Intent intent
, int flags
, int startId
) {
168 if (!intent
.hasExtra(KEY_ACCOUNT
) || !intent
.hasExtra(KEY_UPLOAD_TYPE
) || !(intent
.hasExtra(KEY_LOCAL_FILE
) || intent
.hasExtra(KEY_FILE
))) {
169 Log
.e(TAG
, "Not enough information provided in intent");
170 return Service
.START_NOT_STICKY
;
172 int uploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
173 if (uploadType
== -1) {
174 Log
.e(TAG
, "Incorrect upload type provided");
175 return Service
.START_NOT_STICKY
;
177 Account account
= intent
.getParcelableExtra(KEY_ACCOUNT
);
179 String
[] localPaths
= null
, remotePaths
= null
, mimeTypes
= null
;
180 OCFile
[] files
= null
;
181 if (uploadType
== UPLOAD_SINGLE_FILE
) {
183 if (intent
.hasExtra(KEY_FILE
)) {
184 files
= new OCFile
[] {intent
.getParcelableExtra(KEY_FILE
) };
187 localPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
188 remotePaths
= new String
[] { intent
.getStringExtra(KEY_REMOTE_FILE
) };
189 mimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
192 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
194 if (intent
.hasExtra(KEY_FILE
)) {
195 files
= (OCFile
[]) intent
.getParcelableArrayExtra(KEY_FILE
); // TODO will this casting work fine?
198 localPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
199 remotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
200 mimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
204 FileDataStorageManager storageManager
= new FileDataStorageManager(account
, getContentResolver());
206 boolean forceOverwrite
= intent
.getBooleanExtra(KEY_FORCE_OVERWRITE
, false
);
207 boolean isInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
208 int localAction
= intent
.getIntExtra(KEY_LOCAL_BEHAVIOUR
, LOCAL_BEHAVIOUR_COPY
);
209 boolean fixed
= false
;
211 fixed
= checkAndFixInstantUploadDirectory(storageManager
); // MUST be done BEFORE calling obtainNewOCFileToUpload
214 if (intent
.hasExtra(KEY_FILE
) && files
== null
) {
215 Log
.e(TAG
, "Incorrect array for OCFiles provided in upload intent");
216 return Service
.START_NOT_STICKY
;
218 } else if (!intent
.hasExtra(KEY_FILE
)) {
219 if (localPaths
== null
) {
220 Log
.e(TAG
, "Incorrect array for local paths provided in upload intent");
221 return Service
.START_NOT_STICKY
;
223 if (remotePaths
== null
) {
224 Log
.e(TAG
, "Incorrect array for remote paths provided in upload intent");
225 return Service
.START_NOT_STICKY
;
227 if (localPaths
.length
!= remotePaths
.length
) {
228 Log
.e(TAG
, "Different number of remote paths and local paths!");
229 return Service
.START_NOT_STICKY
;
232 files
= new OCFile
[localPaths
.length
];
233 for (int i
=0; i
< localPaths
.length
; i
++) {
234 files
[i
] = obtainNewOCFileToUpload(remotePaths
[i
], localPaths
[i
], ((mimeTypes
!=null
)?mimeTypes
[i
]:(String
)null
), storageManager
);
238 OwnCloudVersion ocv
= new OwnCloudVersion(AccountManager
.get(this).getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
239 boolean chunked
= FileUploader
.chunkedUploadIsSupported(ocv
);
240 AbstractList
<String
> requestedUploads
= new Vector
<String
>();
241 String uploadKey
= null
;
242 UploadFileOperation newUpload
= null
;
244 for (int i
=0; i
< files
.length
; i
++) {
245 uploadKey
= buildRemoteName(account
, files
[i
].getRemotePath());
247 newUpload
= new ChunkedUploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
249 newUpload
= new UploadFileOperation(account
, files
[i
], isInstant
, forceOverwrite
, localAction
);
252 newUpload
.setRemoteFolderToBeCreated();
254 mPendingUploads
.putIfAbsent(uploadKey
, newUpload
);
255 newUpload
.addDatatransferProgressListener(this);
256 requestedUploads
.add(uploadKey
);
259 } catch (IllegalArgumentException e
) {
260 Log
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
261 return START_NOT_STICKY
;
263 } catch (IllegalStateException e
) {
264 Log
.e(TAG
, "Bad information provided in intent: " + e
.getMessage());
265 return START_NOT_STICKY
;
267 } catch (Exception e
) {
268 Log
.e(TAG
, "Unexpected exception while processing upload intent", e
);
269 return START_NOT_STICKY
;
273 if (requestedUploads
.size() > 0) {
274 Message msg
= mServiceHandler
.obtainMessage();
276 msg
.obj
= requestedUploads
;
277 mServiceHandler
.sendMessage(msg
);
280 return Service
.START_NOT_STICKY
;
285 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
287 * Implemented to perform cancellation, pause and resume of existing uploads.
290 public IBinder
onBind(Intent arg0
) {
295 * Binder to let client components to perform operations on the queue of uploads.
297 * It provides by itself the available operations.
299 public class FileUploaderBinder
extends Binder
{
302 * Cancels a pending or current upload of a remote file.
304 * @param account Owncloud account where the remote file will be stored.
305 * @param file A file in the queue of pending uploads
307 public void cancel(Account account
, OCFile file
) {
308 UploadFileOperation upload
= null
;
309 synchronized (mPendingUploads
) {
310 upload
= mPendingUploads
.remove(buildRemoteName(account
, file
));
312 if (upload
!= null
) {
319 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
321 * If 'file' is a directory, returns 'true' if some of its descendant files is downloading or waiting to download.
323 * @param account Owncloud account where the remote file will be stored.
324 * @param file A file that could be in the queue of pending uploads
326 public boolean isUploading(Account account
, OCFile file
) {
327 if (account
== null
|| file
== null
) return false
;
328 String targetKey
= buildRemoteName(account
, file
);
329 synchronized (mPendingUploads
) {
330 if (file
.isDirectory()) {
331 // this can be slow if there are many downloads :(
332 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
333 boolean found
= false
;
334 while (it
.hasNext() && !found
) {
335 found
= it
.next().startsWith(targetKey
);
339 return (mPendingUploads
.containsKey(targetKey
));
349 * Upload worker. Performs the pending uploads in the order they were requested.
351 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
353 private static class ServiceHandler
extends Handler
{
354 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
355 FileUploader mService
;
356 public ServiceHandler(Looper looper
, FileUploader service
) {
359 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
364 public void handleMessage(Message msg
) {
365 @SuppressWarnings("unchecked")
366 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
367 if (msg
.obj
!= null
) {
368 Iterator
<String
> it
= requestedUploads
.iterator();
369 while (it
.hasNext()) {
370 mService
.uploadFile(it
.next());
373 mService
.stopSelf(msg
.arg1
);
381 * Core upload method: sends the file(s) to upload
383 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
385 public void uploadFile(String uploadKey
) {
387 synchronized(mPendingUploads
) {
388 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
391 if (mCurrentUpload
!= null
) {
393 notifyUploadStart(mCurrentUpload
);
396 /// prepare client object to send requests to the ownCloud server
397 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
398 mLastAccount
= mCurrentUpload
.getAccount();
399 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
400 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
403 /// create remote folder for instant uploads
404 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
405 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
409 /// perform the upload
410 RemoteOperationResult uploadResult
= null
;
412 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
413 if (uploadResult
.isSuccess()) {
418 synchronized(mPendingUploads
) {
419 mPendingUploads
.remove(uploadKey
);
424 notifyUploadResult(uploadResult
, mCurrentUpload
);
426 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
433 * Saves a OC File after a successful upload.
435 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
436 * specially the modification time and Etag (where available)
438 * TODO refactor this ugly thing
440 private void saveUploadedFile() {
441 OCFile file
= mCurrentUpload
.getFile();
442 long syncDate
= System
.currentTimeMillis();
443 file
.setLastSyncDateForData(syncDate
);
445 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
446 PropFindMethod propfind
= null
;
447 RemoteOperationResult result
= null
;
449 propfind
= new PropFindMethod(mUploadClient
.getBaseUri() + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
450 int status
= mUploadClient
.executeMethod(propfind
);
451 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
453 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
454 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0],
455 mUploadClient
.getBaseUri().getPath());
456 updateOCFile(file
, we
);
457 file
.setLastSyncDateForProperties(syncDate
);
460 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
463 result
= new RemoteOperationResult(isMultiStatus
, status
);
464 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage());
466 } catch (Exception e
) {
467 result
= new RemoteOperationResult(e
);
468 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage(), e
);
471 if (propfind
!= null
)
472 propfind
.releaseConnection();
475 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
476 if (mCurrentUpload
.wasRenamed()) {
477 OCFile oldFile
= mCurrentUpload
.getOldFile();
478 if (oldFile
.fileExists()) {
479 oldFile
.setStoragePath(null
);
480 mStorageManager
.saveFile(oldFile
);
482 } // 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()
485 mStorageManager
.saveFile(file
);
489 private void updateOCFile(OCFile file
, WebdavEntry we
) {
490 file
.setCreationTimestamp(we
.createTimestamp());
491 file
.setFileLength(we
.contentLength());
492 file
.setMimetype(we
.contentType());
493 file
.setModificationTimestamp(we
.modifiedTimestamp());
494 file
.setModificationTimestampAtLastSyncForData(we
.modifiedTimestamp());
495 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
499 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
500 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
501 if (instantUploadDir
== null
) {
502 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
503 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
504 newDir
.setMimetype("DIR");
505 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
506 storageManager
.saveFile(newDir
);
513 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, FileDataStorageManager storageManager
) {
514 OCFile newFile
= new OCFile(remotePath
);
515 newFile
.setStoragePath(localPath
);
516 newFile
.setLastSyncDateForProperties(0);
517 newFile
.setLastSyncDateForData(0);
520 if (localPath
!= null
&& localPath
.length() > 0) {
521 File localFile
= new File(localPath
);
522 newFile
.setFileLength(localFile
.length());
523 newFile
.setLastSyncDateForData(localFile
.lastModified());
524 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
527 if (mimeType
== null
|| mimeType
.length() <= 0) {
529 mimeType
= MimeTypeMap
.getSingleton()
530 .getMimeTypeFromExtension(
531 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
532 } catch (IndexOutOfBoundsException e
) {
533 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
536 if (mimeType
== null
) {
537 mimeType
= "application/octet-stream";
539 newFile
.setMimetype(mimeType
);
542 String parentPath
= new File(remotePath
).getParent();
543 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
544 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
545 if (parentDir
== null
) {
546 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath
);
548 long parentDirId
= parentDir
.getFileId();
549 newFile
.setParentId(parentDirId
);
555 * Creates a status notification to show the upload progress
557 * @param upload Upload operation starting.
559 @SuppressWarnings("deprecation")
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
);