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