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