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