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