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