6d443a9c5fa7e6c90c50723f0659fe2032798e37
[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_FILE_PATH = "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 String targetKey = buildRemoteName(account, file);
328 synchronized (mPendingUploads) {
329 if (file.isDirectory()) {
330 // this can be slow if there are many downloads :(
331 Iterator<String> it = mPendingUploads.keySet().iterator();
332 boolean found = false;
333 while (it.hasNext() && !found) {
334 found = it.next().startsWith(targetKey);
335 }
336 return found;
337 } else {
338 return (mPendingUploads.containsKey(targetKey));
339 }
340 }
341 }
342 }
343
344
345
346
347 /**
348 * Upload worker. Performs the pending uploads in the order they were requested.
349 *
350 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
351 */
352 private static class ServiceHandler extends Handler {
353 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
354 FileUploader mService;
355 public ServiceHandler(Looper looper, FileUploader service) {
356 super(looper);
357 if (service == null)
358 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
359 mService = service;
360 }
361
362 @Override
363 public void handleMessage(Message msg) {
364 @SuppressWarnings("unchecked")
365 AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
366 if (msg.obj != null) {
367 Iterator<String> it = requestedUploads.iterator();
368 while (it.hasNext()) {
369 mService.uploadFile(it.next());
370 }
371 }
372 mService.stopSelf(msg.arg1);
373 }
374 }
375
376
377
378
379 /**
380 * Core upload method: sends the file(s) to upload
381 *
382 * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
383 */
384 public void uploadFile(String uploadKey) {
385
386 synchronized(mPendingUploads) {
387 mCurrentUpload = mPendingUploads.get(uploadKey);
388 }
389
390 if (mCurrentUpload != null) {
391
392 notifyUploadStart(mCurrentUpload);
393
394
395 /// prepare client object to send requests to the ownCloud server
396 if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
397 mLastAccount = mCurrentUpload.getAccount();
398 mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
399 mUploadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
400 }
401
402 /// create remote folder for instant uploads
403 if (mCurrentUpload.isRemoteFolderToBeCreated()) {
404 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
405 }
406
407
408 /// perform the upload
409 RemoteOperationResult uploadResult = null;
410 try {
411 uploadResult = mCurrentUpload.execute(mUploadClient);
412 if (uploadResult.isSuccess()) {
413 saveUploadedFile();
414 }
415
416 } finally {
417 synchronized(mPendingUploads) {
418 mPendingUploads.remove(uploadKey);
419 }
420 }
421
422 /// notify result
423 notifyUploadResult(uploadResult, mCurrentUpload);
424
425 sendFinalBroadcast(mCurrentUpload, uploadResult);
426
427 }
428
429 }
430
431 /**
432 * Saves a OC File after a successful upload.
433 *
434 * A PROPFIND is necessary to keep the props in the local database synchronized with the server,
435 * specially the modification time and Etag (where available)
436 *
437 * TODO refactor this ugly thing
438 */
439 private void saveUploadedFile() {
440 OCFile file = mCurrentUpload.getFile();
441 long syncDate = System.currentTimeMillis();
442 file.setLastSyncDateForData(syncDate);
443
444 /// new PROPFIND to keep data consistent with server in theory, should return the same we already have
445 PropFindMethod propfind = null;
446 RemoteOperationResult result = null;
447 try {
448 propfind = new PropFindMethod(mUploadClient.getBaseUri() + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()));
449 int status = mUploadClient.executeMethod(propfind);
450 boolean isMultiStatus = (status == HttpStatus.SC_MULTI_STATUS);
451 if (isMultiStatus) {
452 MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
453 WebdavEntry we = new WebdavEntry(resp.getResponses()[0],
454 mUploadClient.getBaseUri().getPath());
455 updateOCFile(file, we);
456 file.setLastSyncDateForProperties(syncDate);
457
458 } else {
459 mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
460 }
461
462 result = new RemoteOperationResult(isMultiStatus, status);
463 Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage());
464
465 } catch (Exception e) {
466 result = new RemoteOperationResult(e);
467 Log.e(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": " + result.getLogMessage(), e);
468
469 } finally {
470 if (propfind != null)
471 propfind.releaseConnection();
472 }
473
474 /// maybe this would be better as part of UploadFileOperation... or maybe all this method
475 if (mCurrentUpload.wasRenamed()) {
476 OCFile oldFile = mCurrentUpload.getOldFile();
477 if (oldFile.fileExists()) {
478 oldFile.setStoragePath(null);
479 mStorageManager.saveFile(oldFile);
480
481 } // 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()
482 }
483
484 mStorageManager.saveFile(file);
485 }
486
487
488 private void updateOCFile(OCFile file, WebdavEntry we) {
489 file.setCreationTimestamp(we.createTimestamp());
490 file.setFileLength(we.contentLength());
491 file.setMimetype(we.contentType());
492 file.setModificationTimestamp(we.modifiedTimesamp());
493 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
494 }
495
496
497 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
498 OCFile instantUploadDir = storageManager.getFileByPath(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
499 if (instantUploadDir == null) {
500 // first instant upload in the account, or never account not synchronized after the remote InstantUpload folder was created
501 OCFile newDir = new OCFile(InstantUploadBroadcastReceiver.INSTANT_UPLOAD_DIR);
502 newDir.setMimetype("DIR");
503 newDir.setParentId(storageManager.getFileByPath(OCFile.PATH_SEPARATOR).getFileId());
504 storageManager.saveFile(newDir);
505 return true;
506 }
507 return false;
508 }
509
510
511 private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType, FileDataStorageManager storageManager) {
512 OCFile newFile = new OCFile(remotePath);
513 newFile.setStoragePath(localPath);
514 newFile.setLastSyncDateForProperties(0);
515 newFile.setLastSyncDateForData(0);
516
517 // size
518 if (localPath != null && localPath.length() > 0) {
519 File localFile = new File(localPath);
520 newFile.setFileLength(localFile.length());
521 newFile.setLastSyncDateForData(localFile.lastModified());
522 } // don't worry about not assigning size, the problems with localPath are checked when the UploadFileOperation instance is created
523
524 // MIME type
525 if (mimeType == null || mimeType.length() <= 0) {
526 try {
527 mimeType = MimeTypeMap.getSingleton()
528 .getMimeTypeFromExtension(
529 remotePath.substring(remotePath.lastIndexOf('.') + 1));
530 } catch (IndexOutOfBoundsException e) {
531 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
532 }
533 }
534 if (mimeType == null) {
535 mimeType = "application/octet-stream";
536 }
537 newFile.setMimetype(mimeType);
538
539 // parent dir
540 String parentPath = new File(remotePath).getParent();
541 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR ;
542 OCFile parentDir = storageManager.getFileByPath(parentPath);
543 if (parentDir == null) {
544 throw new IllegalStateException("Can not upload a file to a non existing remote location: " + parentPath);
545 }
546 long parentDirId = parentDir.getFileId();
547 newFile.setParentId(parentDirId);
548 return newFile;
549 }
550
551
552 /**
553 * Creates a status notification to show the upload progress
554 *
555 * @param upload Upload operation starting.
556 */
557 private void notifyUploadStart(UploadFileOperation upload) {
558 /// create status notification with a progress bar
559 mLastPercent = 0;
560 mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker), System.currentTimeMillis());
561 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
562 mDefaultNotificationContentView = mNotification.contentView;
563 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
564 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
565 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.uploader_upload_in_progress_content), 0, new File(upload.getStoragePath()).getName()));
566 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
567
568 /// includes a pending intent in the notification showing the details view of the file
569 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
570 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
571 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
572 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
573 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
574
575 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
576 }
577
578
579 /**
580 * Callback method to update the progress bar in the status notification
581 */
582 @Override
583 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
584 int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));
585 if (percent != mLastPercent) {
586 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
587 String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
588 mNotification.contentView.setTextViewText(R.id.status_text, text);
589 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
590 }
591 mLastPercent = percent;
592 }
593
594
595 /**
596 * Callback method to update the progress bar in the status notification (old version)
597 */
598 @Override
599 public void onTransferProgress(long progressRate) {
600 // NOTHING TO DO HERE ANYMORE
601 }
602
603
604 /**
605 * Updates the status notification with the result of an upload operation.
606 *
607 * @param uploadResult Result of the upload operation.
608 * @param upload Finished upload operation
609 */
610 private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
611 if (uploadResult.isCancelled()) {
612 /// cancelled operation -> silent removal of progress notification
613 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
614
615 } else if (uploadResult.isSuccess()) {
616 /// success -> silent update of progress notification to success message
617 mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove the ongoing flag
618 mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
619 mNotification.contentView = mDefaultNotificationContentView;
620
621 /// includes a pending intent in the notification showing the details view of the file
622 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
623 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
624 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
625 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
626 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), showDetailsIntent, 0);
627
628 mNotification.setLatestEventInfo( getApplicationContext(),
629 getString(R.string.uploader_upload_succeeded_ticker),
630 String.format(getString(R.string.uploader_upload_succeeded_content_single), (new File(upload.getStoragePath())).getName()),
631 mNotification.contentIntent);
632
633 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
634
635 /* Notification about multiple uploads: pending of update
636 mNotification.setLatestEventInfo( getApplicationContext(),
637 getString(R.string.uploader_upload_succeeded_ticker),
638 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
639 mNotification.contentIntent);
640 */
641
642 } else {
643 /// fail -> explicit failure notification
644 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
645 Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
646 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
647 // TODO put something smart in the contentIntent below
648 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
649
650 String content = null;
651 if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL ||
652 uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
653 // TODO we need a class to provide error messages for the users from a RemoteOperationResult and a RemoteOperation
654 content = String.format(getString(R.string.error__upload__local_file_not_copied), (new File(upload.getStoragePath())).getName(), getString(R.string.app_name));
655 } else {
656 content = String.format(getString(R.string.uploader_upload_failed_content_single), (new File(upload.getStoragePath())).getName());
657 }
658 finalNotification.setLatestEventInfo( getApplicationContext(),
659 getString(R.string.uploader_upload_failed_ticker),
660 content,
661 finalNotification.contentIntent);
662
663 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
664
665 /* Notification about multiple uploads failure: pending of update
666 finalNotification.setLatestEventInfo( getApplicationContext(),
667 getString(R.string.uploader_upload_failed_ticker),
668 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mTotalFilesToSend),
669 finalNotification.contentIntent);
670 } */
671 }
672
673 }
674
675
676 /**
677 * Sends a broadcast in order to the interested activities can update their view
678 *
679 * @param upload Finished upload operation
680 * @param uploadResult Result of the upload operation
681 */
682 private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
683 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
684 end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote path, after possible automatic renaming
685 if (upload.wasRenamed()) {
686 end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
687 }
688 end.putExtra(EXTRA_FILE_PATH, upload.getStoragePath());
689 end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
690 end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
691 sendStickyBroadcast(end);
692 }
693
694
695 }