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_FILE_PATH
= "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 String targetKey
= buildRemoteName(account
, file
);
328 synchronized (mPendingUploads
) {
329 if (file
.isDirectory()) {
330 // this can be slow if there are many downloads :(
331 Iterator
<String
> it
= mPendingUploads
.keySet().iterator();
332 boolean found
= false
;
333 while (it
.hasNext() && !found
) {
334 found
= it
.next().startsWith(targetKey
);
338 return (mPendingUploads
.containsKey(targetKey
));
348 * Upload worker. Performs the pending uploads in the order they were requested.
350 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
352 private static class ServiceHandler
extends Handler
{
353 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
354 FileUploader mService
;
355 public ServiceHandler(Looper looper
, FileUploader service
) {
358 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
363 public void handleMessage(Message msg
) {
364 @SuppressWarnings("unchecked")
365 AbstractList
<String
> requestedUploads
= (AbstractList
<String
>) msg
.obj
;
366 if (msg
.obj
!= null
) {
367 Iterator
<String
> it
= requestedUploads
.iterator();
368 while (it
.hasNext()) {
369 mService
.uploadFile(it
.next());
372 mService
.stopSelf(msg
.arg1
);
380 * Core upload method: sends the file(s) to upload
382 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
384 public void uploadFile(String uploadKey
) {
386 synchronized(mPendingUploads
) {
387 mCurrentUpload
= mPendingUploads
.get(uploadKey
);
390 if (mCurrentUpload
!= null
) {
392 notifyUploadStart(mCurrentUpload
);
395 /// prepare client object to send requests to the ownCloud server
396 if (mUploadClient
== null
|| !mLastAccount
.equals(mCurrentUpload
.getAccount())) {
397 mLastAccount
= mCurrentUpload
.getAccount();
398 mStorageManager
= new FileDataStorageManager(mLastAccount
, getContentResolver());
399 mUploadClient
= OwnCloudClientUtils
.createOwnCloudClient(mLastAccount
, getApplicationContext());
402 /// create remote folder for instant uploads
403 if (mCurrentUpload
.isRemoteFolderToBeCreated()) {
404 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
408 /// perform the upload
409 RemoteOperationResult uploadResult
= null
;
411 uploadResult
= mCurrentUpload
.execute(mUploadClient
);
412 if (uploadResult
.isSuccess()) {
417 synchronized(mPendingUploads
) {
418 mPendingUploads
.remove(uploadKey
);
423 notifyUploadResult(uploadResult
, mCurrentUpload
);
425 sendFinalBroadcast(mCurrentUpload
, uploadResult
);
432 * Saves a OC File after a successful upload.
434 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
435 * specially the modification time and Etag (where available)
437 * TODO refactor this ugly thing
439 private void saveUploadedFile() {
440 OCFile file
= mCurrentUpload
.getFile();
441 long syncDate
= System
.currentTimeMillis();
442 file
.setLastSyncDateForData(syncDate
);
444 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
445 PropFindMethod propfind
= null
;
446 RemoteOperationResult result
= null
;
448 propfind
= new PropFindMethod(mUploadClient
.getBaseUri() + WebdavUtils
.encodePath(mCurrentUpload
.getRemotePath()));
449 int status
= mUploadClient
.executeMethod(propfind
);
450 boolean isMultiStatus
= (status
== HttpStatus
.SC_MULTI_STATUS
);
452 MultiStatus resp
= propfind
.getResponseBodyAsMultiStatus();
453 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0],
454 mUploadClient
.getBaseUri().getPath());
455 updateOCFile(file
, we
);
456 file
.setLastSyncDateForProperties(syncDate
);
459 mUploadClient
.exhaustResponse(propfind
.getResponseBodyAsStream());
462 result
= new RemoteOperationResult(isMultiStatus
, status
);
463 Log
.i(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage());
465 } catch (Exception e
) {
466 result
= new RemoteOperationResult(e
);
467 Log
.e(TAG
, "Update: synchronizing properties for uploaded " + mCurrentUpload
.getRemotePath() + ": " + result
.getLogMessage(), e
);
470 if (propfind
!= null
)
471 propfind
.releaseConnection();
474 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
475 if (mCurrentUpload
.wasRenamed()) {
476 OCFile oldFile
= mCurrentUpload
.getOldFile();
477 if (oldFile
.fileExists()) {
478 oldFile
.setStoragePath(null
);
479 mStorageManager
.saveFile(oldFile
);
481 } // 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()
484 mStorageManager
.saveFile(file
);
488 private void updateOCFile(OCFile file
, WebdavEntry we
) {
489 file
.setCreationTimestamp(we
.createTimestamp());
490 file
.setFileLength(we
.contentLength());
491 file
.setMimetype(we
.contentType());
492 file
.setModificationTimestamp(we
.modifiedTimesamp());
493 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
497 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager
) {
498 OCFile instantUploadDir
= storageManager
.getFileByPath(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
499 if (instantUploadDir
== null
) {
500 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
501 OCFile newDir
= new OCFile(InstantUploadBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
502 newDir
.setMimetype("DIR");
503 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
504 storageManager
.saveFile(newDir
);
511 private OCFile
obtainNewOCFileToUpload(String remotePath
, String localPath
, String mimeType
, FileDataStorageManager storageManager
) {
512 OCFile newFile
= new OCFile(remotePath
);
513 newFile
.setStoragePath(localPath
);
514 newFile
.setLastSyncDateForProperties(0);
515 newFile
.setLastSyncDateForData(0);
518 if (localPath
!= null
&& localPath
.length() > 0) {
519 File localFile
= new File(localPath
);
520 newFile
.setFileLength(localFile
.length());
521 newFile
.setLastSyncDateForData(localFile
.lastModified());
522 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
525 if (mimeType
== null
|| mimeType
.length() <= 0) {
527 mimeType
= MimeTypeMap
.getSingleton()
528 .getMimeTypeFromExtension(
529 remotePath
.substring(remotePath
.lastIndexOf('.') + 1));
530 } catch (IndexOutOfBoundsException e
) {
531 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + remotePath
);
534 if (mimeType
== null
) {
535 mimeType
= "application/octet-stream";
537 newFile
.setMimetype(mimeType
);
540 String parentPath
= new File(remotePath
).getParent();
541 parentPath
= parentPath
.endsWith(OCFile
.PATH_SEPARATOR
) ? parentPath
: parentPath
+ OCFile
.PATH_SEPARATOR
;
542 OCFile parentDir
= storageManager
.getFileByPath(parentPath
);
543 if (parentDir
== null
) {
544 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath
);
546 long parentDirId
= parentDir
.getFileId();
547 newFile
.setParentId(parentDirId
);
553 * Creates a status notification to show the upload progress
555 * @param upload Upload operation starting.
557 private void notifyUploadStart(UploadFileOperation upload
) {
558 /// create status notification with a progress bar
560 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
561 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
562 mDefaultNotificationContentView
= mNotification
.contentView
;
563 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
564 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
565 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.uploader_upload_in_progress_content
), 0, new File(upload
.getStoragePath()).getName()));
566 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
568 /// includes a pending intent in the notification showing the details view of the file
569 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
570 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
571 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
572 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
573 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
575 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
580 * Callback method to update the progress bar in the status notification
583 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String fileName
) {
584 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
585 if (percent
!= mLastPercent
) {
586 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
587 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, fileName
);
588 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
589 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
591 mLastPercent
= percent
;
596 * Callback method to update the progress bar in the status notification (old version)
599 public void onTransferProgress(long progressRate
) {
600 // NOTHING TO DO HERE ANYMORE
605 * Updates the status notification with the result of an upload operation.
607 * @param uploadResult Result of the upload operation.
608 * @param upload Finished upload operation
610 private void notifyUploadResult(RemoteOperationResult uploadResult
, UploadFileOperation upload
) {
611 if (uploadResult
.isCancelled()) {
612 /// cancelled operation -> silent removal of progress notification
613 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
615 } else if (uploadResult
.isSuccess()) {
616 /// success -> silent update of progress notification to success message
617 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
618 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
619 mNotification
.contentView
= mDefaultNotificationContentView
;
621 /// includes a pending intent in the notification showing the details view of the file
622 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
623 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, upload
.getFile());
624 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, upload
.getAccount());
625 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
626 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), showDetailsIntent
, 0);
628 mNotification
.setLatestEventInfo( getApplicationContext(),
629 getString(R
.string
.uploader_upload_succeeded_ticker
),
630 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), (new File(upload
.getStoragePath())).getName()),
631 mNotification
.contentIntent
);
633 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
635 /* Notification about multiple uploads: pending of update
636 mNotification.setLatestEventInfo( getApplicationContext(),
637 getString(R.string.uploader_upload_succeeded_ticker),
638 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
639 mNotification.contentIntent);
643 /// fail -> explicit failure notification
644 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
645 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
646 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
647 // TODO put something smart in the contentIntent below
648 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
650 String content
= null
;
651 if (uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_FULL
||
652 uploadResult
.getCode() == ResultCode
.LOCAL_STORAGE_NOT_COPIED
) {
653 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
654 content
= String
.format(getString(R
.string
.error__upload__local_file_not_copied
), (new File(upload
.getStoragePath())).getName(), getString(R
.string
.app_name
));
656 content
= String
.format(getString(R
.string
.uploader_upload_failed_content_single
), (new File(upload
.getStoragePath())).getName());
658 finalNotification
.setLatestEventInfo( getApplicationContext(),
659 getString(R
.string
.uploader_upload_failed_ticker
),
661 finalNotification
.contentIntent
);
663 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
665 /* Notification about multiple uploads failure: pending of update
666 finalNotification.setLatestEventInfo( getApplicationContext(),
667 getString(R.string.uploader_upload_failed_ticker),
668 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
669 finalNotification.contentIntent);
677 * Sends a broadcast in order to the interested activities can update their view
679 * @param upload Finished upload operation
680 * @param uploadResult Result of the upload operation
682 private void sendFinalBroadcast(UploadFileOperation upload
, RemoteOperationResult uploadResult
) {
683 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
684 end
.putExtra(EXTRA_REMOTE_PATH
, upload
.getRemotePath()); // real remote path, after possible automatic renaming
685 if (upload
.wasRenamed()) {
686 end
.putExtra(EXTRA_OLD_REMOTE_PATH
, upload
.getOldFile().getRemotePath());
688 end
.putExtra(EXTRA_FILE_PATH
, upload
.getStoragePath());
689 end
.putExtra(ACCOUNT_NAME
, upload
.getAccount().name
);
690 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
.isSuccess());
691 sendStickyBroadcast(end
);