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