Fixed bug: inconsistency in isDown() state due to old OCFile object being saved in...
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileUploader.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
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.
8 *
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.
13 *
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/>.
16 *
17 */
18
19 package com.owncloud.android.files.services;
20
21 import java.io.File;
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;
27
28 import org.apache.http.HttpStatus;
29 import org.apache.jackrabbit.webdav.MultiStatus;
30 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
31
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.ui.activity.FileDetailActivity;
40 import com.owncloud.android.ui.fragment.FileDetailFragment;
41 import com.owncloud.android.utils.OwnCloudVersion;
42
43 import eu.alefzero.webdav.OnDatatransferProgressListener;
44 import eu.alefzero.webdav.WebdavEntry;
45 import eu.alefzero.webdav.WebdavUtils;
46
47 import com.owncloud.android.network.OwnCloudClientUtils;
48
49 import android.accounts.Account;
50 import android.accounts.AccountManager;
51 import android.app.Notification;
52 import android.app.NotificationManager;
53 import android.app.PendingIntent;
54 import android.app.Service;
55 import android.content.Intent;
56 import android.os.Binder;
57 import android.os.Handler;
58 import android.os.HandlerThread;
59 import android.os.IBinder;
60 import android.os.Looper;
61 import android.os.Message;
62 import android.os.Process;
63 import android.util.Log;
64 import android.webkit.MimeTypeMap;
65 import android.widget.RemoteViews;
66
67 import com.owncloud.android.R;
68 import eu.alefzero.webdav.WebdavClient;
69
70 public class FileUploader extends Service implements OnDatatransferProgressListener {
71
72 public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
73 public static final String EXTRA_PARENT_DIR_ID = "PARENT_DIR_ID";
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_FILE_PATH = "FILE_PATH";
77 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
78
79 public static final String KEY_FILE = "FILE";
80 public static final String KEY_LOCAL_FILE = "LOCAL_FILE"; // TODO remove this as a possible input argument ; use KEY_FILE everywhere
81 public static final String KEY_REMOTE_FILE = "REMOTE_FILE"; // TODO remove this as a possible input argument ; use KEY_FILE everywhere
82 public static final String KEY_MIME_TYPE = "MIME_TYPE";
83
84 public static final String KEY_ACCOUNT = "ACCOUNT";
85
86 public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
87 public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
88 public static final String KEY_INSTANT_UPLOAD = "INSTANT_UPLOAD";
89
90 public static final int UPLOAD_SINGLE_FILE = 0;
91 public static final int UPLOAD_MULTIPLE_FILES = 1;
92
93 private static final String TAG = FileUploader.class.getSimpleName();
94
95 private Looper mServiceLooper;
96 private ServiceHandler mServiceHandler;
97 private IBinder mBinder;
98 private WebdavClient mUploadClient = null;
99 private Account mLastAccount = null;
100 private FileDataStorageManager mStorageManager;
101
102 private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
103 private UploadFileOperation mCurrentUpload = null;
104
105 private NotificationManager mNotificationManager;
106 private Notification mNotification;
107 private int mLastPercent;
108 private RemoteViews mDefaultNotificationContentView;
109
110
111 /**
112 * Builds a key for mPendingUploads from the account and file to upload
113 *
114 * @param account Account where the file to download is stored
115 * @param file File to download
116 */
117 private String buildRemoteName(Account account, OCFile file) {
118 return account.name + file.getRemotePath();
119 }
120
121 private String buildRemoteName(Account account, String remotePath) {
122 return account.name + remotePath;
123 }
124
125
126 /**
127 * Checks if an ownCloud server version should support chunked uploads.
128 *
129 * @param version OwnCloud version instance corresponding to an ownCloud server.
130 * @return 'True' if the ownCloud server with version supports chunked uploads.
131 */
132 private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
133 return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
134 }
135
136
137
138 /**
139 * Service initialization
140 */
141 @Override
142 public void onCreate() {
143 super.onCreate();
144 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
145 HandlerThread thread = new HandlerThread("FileUploaderThread",
146 Process.THREAD_PRIORITY_BACKGROUND);
147 thread.start();
148 mServiceLooper = thread.getLooper();
149 mServiceHandler = new ServiceHandler(mServiceLooper, this);
150 mBinder = new FileUploaderBinder();
151 }
152
153
154 /**
155 * Entry point to add one or several files to the queue of uploads.
156 *
157 * New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working
158 * although the caller activity goes away.
159 */
160 @Override
161 public int onStartCommand(Intent intent, int flags, int startId) {
162 if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE) || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
163 Log.e(TAG, "Not enough information provided in intent");
164 return Service.START_NOT_STICKY;
165 }
166 int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
167 if (uploadType == -1) {
168 Log.e(TAG, "Incorrect upload type provided");
169 return Service.START_NOT_STICKY;
170 }
171 Account account = intent.getParcelableExtra(KEY_ACCOUNT);
172
173 String[] localPaths = null, remotePaths = null, mimeTypes = null;
174 OCFile[] files = null;
175 if (uploadType == UPLOAD_SINGLE_FILE) {
176
177 if (intent.hasExtra(KEY_FILE)) {
178 files = new OCFile[] {intent.getParcelableExtra(KEY_FILE) };
179
180 } else {
181 localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
182 remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
183 mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
184 }
185
186 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
187
188 if (intent.hasExtra(KEY_FILE)) {
189 files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO will this casting work fine?
190
191 } else {
192 localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
193 remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
194 mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
195 }
196 }
197
198 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
199
200 if (intent.hasExtra(KEY_FILE) && files == null) {
201 Log.e(TAG, "Incorrect array for OCFiles provided in upload intent");
202 return Service.START_NOT_STICKY;
203
204 } else if (!intent.hasExtra(KEY_FILE)) {
205 if (localPaths == null) {
206 Log.e(TAG, "Incorrect array for local paths provided in upload intent");
207 return Service.START_NOT_STICKY;
208 }
209 if (remotePaths == null) {
210 Log.e(TAG, "Incorrect array for remote paths provided in upload intent");
211 return Service.START_NOT_STICKY;
212 }
213 if (localPaths.length != remotePaths.length) {
214 Log.e(TAG, "Different number of remote paths and local paths!");
215 return Service.START_NOT_STICKY;
216 }
217
218 files = new OCFile[localPaths.length];
219 for (int i=0; i < localPaths.length; i++) {
220 files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes!=null)?mimeTypes[i]:(String)null), storageManager);
221 }
222 }
223
224 boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
225 boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
226
227 OwnCloudVersion ocv = new OwnCloudVersion(AccountManager.get(this).getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
228 boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
229 AbstractList<String> requestedUploads = new Vector<String>();
230 String uploadKey = null;
231 UploadFileOperation newUpload = null;
232 boolean fixed = false;
233 if (isInstant) {
234 fixed = checkAndFixInstantUploadDirectory(storageManager);
235 }
236 try {
237 for (int i=0; i < files.length; i++) {
238 uploadKey = buildRemoteName(account, files[i].getRemotePath());
239 if (chunked) {
240 newUpload = new ChunkedUploadFileOperation(account, files[i], isInstant, forceOverwrite);
241 } else {
242 newUpload = new UploadFileOperation(account, files[i], isInstant, forceOverwrite);
243 }
244 if (fixed && i==0) {
245 newUpload.setRemoteFolderToBeCreated();
246 }
247 mPendingUploads.putIfAbsent(uploadKey, newUpload);
248 newUpload.addDatatransferProgressListener(this);
249 requestedUploads.add(uploadKey);
250 }
251
252 } catch (IllegalArgumentException e) {
253 Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
254 return START_NOT_STICKY;
255
256 } catch (IllegalStateException e) {
257 Log.e(TAG, "Bad information provided in intent: " + e.getMessage());
258 return START_NOT_STICKY;
259
260 } catch (Exception e) {
261 Log.e(TAG, "Unexpected exception while processing upload intent", e);
262 return START_NOT_STICKY;
263
264 }
265
266 if (requestedUploads.size() > 0) {
267 Message msg = mServiceHandler.obtainMessage();
268 msg.arg1 = startId;
269 msg.obj = requestedUploads;
270 mServiceHandler.sendMessage(msg);
271 }
272
273 return Service.START_NOT_STICKY;
274 }
275
276
277 /**
278 * Provides a binder object that clients can use to perform operations on the queue of uploads, excepting the addition of new files.
279 *
280 * Implemented to perform cancellation, pause and resume of existing uploads.
281 */
282 @Override
283 public IBinder onBind(Intent arg0) {
284 return mBinder;
285 }
286
287 /**
288 * Binder to let client components to perform operations on the queue of uploads.
289 *
290 * It provides by itself the available operations.
291 */
292 public class FileUploaderBinder extends Binder {
293
294 /**
295 * Cancels a pending or current upload of a remote file.
296 *
297 * @param account Owncloud account where the remote file will be stored.
298 * @param file A file in the queue of pending uploads
299 */
300 public void cancel(Account account, OCFile file) {
301 UploadFileOperation upload = null;
302 synchronized (mPendingUploads) {
303 upload = mPendingUploads.remove(buildRemoteName(account, file));
304 }
305 if (upload != null) {
306 upload.cancel();
307 }
308 }
309
310
311 /**
312 * Returns True when the file described by 'file' is being uploaded to the ownCloud account 'account' or waiting for it
313 *
314 * @param account Owncloud account where the remote file will be stored.
315 * @param file A file that could be in the queue of pending uploads
316 */
317 public boolean isUploading(Account account, OCFile file) {
318 synchronized (mPendingUploads) {
319 return (mPendingUploads.containsKey(buildRemoteName(account, file)));
320 }
321 }
322 }
323
324
325
326
327 /**
328 * Upload worker. Performs the pending uploads in the order they were requested.
329 *
330 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
331 */
332 private static class ServiceHandler extends Handler {
333 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
334 FileUploader mService;
335 public ServiceHandler(Looper looper, FileUploader service) {
336 super(looper);
337 if (service == null)
338 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
339 mService = service;
340 }
341
342 @Override
343 public void handleMessage(Message msg) {
344 @SuppressWarnings("unchecked")
345 AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
346 if (msg.obj != null) {
347 Iterator<String> it = requestedUploads.iterator();
348 while (it.hasNext()) {
349 mService.uploadFile(it.next());
350 }
351 }
352 mService.stopSelf(msg.arg1);
353 }
354 }
355
356
357
358
359 /**
360 * Core upload method: sends the file(s) to upload
361 *
362 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
363 */
364 public void uploadFile(String uploadKey) {
365
366 synchronized(mPendingUploads) {
367 mCurrentUpload = mPendingUploads.get(uploadKey);
368 }
369
370 if (mCurrentUpload != null) {
371
372 notifyUploadStart(mCurrentUpload);
373
374
375 /// prepare client object to send requests to the ownCloud server
376 if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
377 mLastAccount = mCurrentUpload.getAccount();
378 mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
379 mUploadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
380 }
381
382 /// create remote folder for instant uploads
383 if (mCurrentUpload.isRemoteFolderToBeCreated()) {
384 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
385 }
386
387
388 /// perform the upload
389 RemoteOperationResult uploadResult = null;
390 try {
391 uploadResult = mCurrentUpload.execute(mUploadClient);
392 if (uploadResult.isSuccess()) {
393 saveUploadedFile();
394 }
395
396 } finally {
397 synchronized(mPendingUploads) {
398 mPendingUploads.remove(uploadKey);
399 }
400 }
401
402 /// notify result
403 notifyUploadResult(uploadResult, mCurrentUpload);
404
405 sendFinalBroadcast(mCurrentUpload, uploadResult);
406
407 }
408
409 }
410
411 /**
412 * Saves a OC File after a successful upload.
413 *
414 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
415 * specially the modification time and Etag (where available)
416 *
417 * TODO refactor this ugly thing
418 */
419 private void saveUploadedFile() {
420 OCFile file = mCurrentUpload.getFile();
421
422 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
423 PropFindMethod propfind = null;
424 RemoteOperationResult result = null;
425 long syncDate = System.currentTimeMillis();
426 try {
427 propfind = new PropFindMethod(mUploadClient.getBaseUri() + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()));
428 int status = mUploadClient.executeMethod(propfind);
429 boolean isMultiStatus = (status == HttpStatus.SC_MULTI_STATUS);
430 if (isMultiStatus) {
431 MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
432 WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
433 mUploadClient.getBaseUri().getPath());
434 OCFile newFile = fillOCFile(we);
435 newFile.setStoragePath(file.getStoragePath());
436 newFile.setKeepInSync(file.keepInSync());
437 newFile.setLastSyncDateForProperties(syncDate);
438 file = newFile;
439
440 } else {
441 mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
442 }
443
444 result = new RemoteOperationResult(isMultiStatus, status);
445 Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage());
446
447 } catch (Exception e) {
448 result = new RemoteOperationResult(e);
449 Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage(), e);
450
451 } finally {
452 if (propfind != null)
453 propfind.releaseConnection();
454 }
455
456 file.setLastSyncDateForData(syncDate); // this is right, no matter if the PROPFIND was successful or not
457
458 if (!result.isSuccess() && !mCurrentUpload.getRemotePath().equals(file.getRemotePath())) {
459 // true when the file was automatically renamed to avoid an overwrite ; yes, this is a bit obscure...
460 OCFile newFile = new OCFile(mCurrentUpload.getRemotePath());
461 newFile.setCreationTimestamp(file.getCreationTimestamp());
462 newFile.setFileLength(file.getFileLength());
463 newFile.setMimetype(file.getMimetype());
464 newFile.setModificationTimestamp(file.getModificationTimestamp());
465 newFile.setLastSyncDateForProperties(file.getLastSyncDateForProperties());
466 newFile.setStoragePath(file.getStoragePath());
467 newFile.setKeepInSync(file.keepInSync());
468 // newFile.setEtag(file.getEtag())
469 file = newFile;
470 }
471
472 mStorageManager.saveFile(file);
473 }
474
475
476 private OCFile fillOCFile(WebdavEntry we) {
477 OCFile file = new OCFile(we.decodedPath());
478 file.setCreationTimestamp(we.createTimestamp());
479 file.setFileLength(we.contentLength());
480 file.setMimetype(we.contentType());
481 file.setModificationTimestamp(we.modifiedTimesamp());
482 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
483 return file;
484 }
485
486
487 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
488 OCFile instantUploadDir = storageManager.getFileByPath(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
489 if (instantUploadDir == null) {
490 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
491 OCFile newDir = new OCFile(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
492 newDir.setMimetype("DIR");
493 newDir.setParentId(storageManager.getFileByPath(OCFile.PATH_SEPARATOR).getFileId());
494 storageManager.saveFile(newDir);
495 return true;
496 }
497 return false;
498 }
499
500
501 private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType, FileDataStorageManager storageManager) {
502 OCFile newFile = new OCFile(remotePath);
503 newFile.setStoragePath(localPath);
504 newFile.setLastSyncDateForProperties(0);
505 newFile.setLastSyncDateForData(0);
506
507 // size
508 if (localPath != null && localPath.length() > 0) {
509 File localFile = new File(localPath);
510 newFile.setFileLength(localFile.length());
511 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
512
513 // MIME type
514 if (mimeType == null || mimeType.length() <= 0) {
515 try {
516 mimeType = MimeTypeMap.getSingleton()
517 .getMimeTypeFromExtension(
518 remotePath.substring(remotePath.lastIndexOf('.') + 1));
519 } catch (IndexOutOfBoundsException e) {
520 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
521 }
522 }
523 if (mimeType == null) {
524 mimeType = "application/octet-stream";
525 }
526 newFile.setMimetype(mimeType);
527
528 // parent dir
529 String parentPath = new File(remotePath).getParent();
530 parentPath = parentPath.endsWith("/")?parentPath:parentPath+"/" ;
531 OCFile parentDir = storageManager.getFileByPath(parentPath);
532 if (parentDir == null) {
533 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath);
534 }
535 long parentDirId = parentDir.getFileId();
536 newFile.setParentId(parentDirId);
537 return newFile;
538 }
539
540
541 /**
542 * Creates a status notification to show the upload progress
543 *
544 * @param upload Upload operation starting.
545 */
546 private void notifyUploadStart(UploadFileOperation upload) {
547 /// create status notification with a progress bar
548 mLastPercent = 0;
549 mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker), System.currentTimeMillis());
550 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
551 mDefaultNotificationContentView = mNotification.contentView;
552 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
553 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
554 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.uploader_upload_in_progress_content), 0, new File(upload.getStoragePath()).getName()));
555 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
556
557 /// includes a pending intent in the notification showing the details view of the file
558 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
559 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
560 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
561 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
562 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
563
564 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
565 }
566
567
568 /**
569 * Callback method to update the progress bar in the status notification
570 */
571 @Override
572 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
573 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
574 if (percent != mLastPercent) {
575 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
576 String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
577 mNotification.contentView.setTextViewText(R.id.status_text, text);
578 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
579 }
580 mLastPercent = percent;
581 }
582
583
584 /**
585 * Callback method to update the progress bar in the status notification (old version)
586 */
587 @Override
588 public void onTransferProgress(long progressRate) {
589 // NOTHING TO DO HERE ANYMORE
590 }
591
592
593 /**
594 * Updates the status notification with the result of an upload operation.
595 *
596 * @param uploadResult Result of the upload operation.
597 * @param upload Finished upload operation
598 */
599 private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
600 if (uploadResult.isCancelled()) {
601 /// cancelled operation -> silent removal of progress notification
602 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
603
604 } else if (uploadResult.isSuccess()) {
605 /// success -> silent update of progress notification to success message
606 mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove the ongoing flag
607 mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
608 mNotification.contentView = mDefaultNotificationContentView;
609
610 /// includes a pending intent in the notification showing the details view of the file
611 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
612 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
613 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
614 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
615 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
616
617 mNotification.setLatestEventInfo( getApplicationContext(),
618 getString(R.string.uploader_upload_succeeded_ticker),
619 String.format(getString(R.string.uploader_upload_succeeded_content_single), (new File(upload.getStoragePath())).getName()),
620 mNotification.contentIntent);
621
622 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
623
624 /* Notification about multiple uploads: pending of update
625 mNotification.setLatestEventInfo( getApplicationContext(),
626 getString(R.string.uploader_upload_succeeded_ticker),
627 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
628 mNotification.contentIntent);
629 */
630
631 } else {
632 /// fail -> explicit failure notification
633 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
634 Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
635 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
636 // TODO put something smart in the contentIntent below
637 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
638 finalNotification.setLatestEventInfo( getApplicationContext(),
639 getString(R.string.uploader_upload_failed_ticker),
640 String.format(getString(R.string.uploader_upload_failed_content_single), (new File(upload.getStoragePath())).getName()),
641 finalNotification.contentIntent);
642
643 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
644
645 /* Notification about multiple uploads failure: pending of update
646 finalNotification.setLatestEventInfo( getApplicationContext(),
647 getString(R.string.uploader_upload_failed_ticker),
648 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
649 finalNotification.contentIntent);
650 } */
651 }
652
653 }
654
655
656 /**
657 * Sends a broadcast in order to the interested activities can update their view
658 *
659 * @param upload Finished upload operation
660 * @param uploadResult Result of the upload operation
661 */
662 private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
663 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
664 end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote path, after possible automatic renaming
665 end.putExtra(EXTRA_FILE_PATH, upload.getStoragePath());
666 end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
667 end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
668 end.putExtra(EXTRA_PARENT_DIR_ID, upload.getFile().getParentId());
669 sendBroadcast(end);
670 }
671
672
673 }