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