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