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