Added CONTRIBUTING.md and THIRD_PARTY.txt
[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.FailedUploadActivity;
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(InstantUploadService.INSTANT_UPLOAD_DIR);
426 // ignoring result fail could just mean that it already exists,
427 // but local database is not synchronized the upload will be
428 // tried anyway
429 }
430
431 // / perform the upload
432 RemoteOperationResult uploadResult = null;
433 try {
434 uploadResult = mCurrentUpload.execute(mUploadClient);
435 if (uploadResult.isSuccess()) {
436 saveUploadedFile();
437 }
438
439 } finally {
440 synchronized (mPendingUploads) {
441 mPendingUploads.remove(uploadKey);
442 Log.i(TAG, "Remove CurrentUploadItem from pending upload Item Map.");
443 }
444 }
445
446 // notify result
447 notifyUploadResult(uploadResult, mCurrentUpload);
448 sendFinalBroadcast(mCurrentUpload, uploadResult);
449
450 }
451
452 }
453
454 /**
455 * Saves a OC File after a successful upload.
456 *
457 * A PROPFIND is necessary to keep the props in the local database
458 * synchronized with the server, specially the modification time and Etag
459 * (where available)
460 *
461 * TODO refactor this ugly thing
462 */
463 private void saveUploadedFile() {
464 OCFile file = mCurrentUpload.getFile();
465 long syncDate = System.currentTimeMillis();
466 file.setLastSyncDateForData(syncDate);
467
468 // / new PROPFIND to keep data consistent with server in theory, should
469 // return the same we already have
470 PropFindMethod propfind = null;
471 RemoteOperationResult result = null;
472 try {
473 propfind = new PropFindMethod(mUploadClient.getBaseUri()
474 + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()));
475 int status = mUploadClient.executeMethod(propfind);
476 boolean isMultiStatus = (status == HttpStatus.SC_MULTI_STATUS);
477 if (isMultiStatus) {
478 MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
479 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], mUploadClient.getBaseUri().getPath());
480 updateOCFile(file, we);
481 file.setLastSyncDateForProperties(syncDate);
482
483 } else {
484 mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
485 }
486
487 result = new RemoteOperationResult(isMultiStatus, status);
488 Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
489 + result.getLogMessage());
490
491 } catch (Exception e) {
492 result = new RemoteOperationResult(e);
493 Log.e(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
494 + result.getLogMessage(), e);
495
496 } finally {
497 if (propfind != null)
498 propfind.releaseConnection();
499 }
500
501 // / maybe this would be better as part of UploadFileOperation... or
502 // maybe all this method
503 if (mCurrentUpload.wasRenamed()) {
504 OCFile oldFile = mCurrentUpload.getOldFile();
505 if (oldFile.fileExists()) {
506 oldFile.setStoragePath(null);
507 mStorageManager.saveFile(oldFile);
508
509 } // else: it was just an automatic renaming due to a name
510 // coincidence; nothing else is needed, the storagePath is right
511 // in the instance returned by mCurrentUpload.getFile()
512 }
513
514 mStorageManager.saveFile(file);
515 }
516
517 private void updateOCFile(OCFile file, WebdavEntry we) {
518 file.setCreationTimestamp(we.createTimestamp());
519 file.setFileLength(we.contentLength());
520 file.setMimetype(we.contentType());
521 file.setModificationTimestamp(we.modifiedTimestamp());
522 file.setModificationTimestampAtLastSyncForData(we.modifiedTimestamp());
523 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where
524 // available
525 }
526
527 private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
528 OCFile instantUploadDir = storageManager.getFileByPath(InstantUploadService.INSTANT_UPLOAD_DIR);
529 if (instantUploadDir == null) {
530 // first instant upload in the account, or never account not
531 // synchronized after the remote InstantUpload folder was created
532 OCFile newDir = new OCFile(InstantUploadService.INSTANT_UPLOAD_DIR);
533 newDir.setMimetype("DIR");
534 OCFile path = storageManager.getFileByPath(OCFile.PATH_SEPARATOR);
535
536 if (path != null) {
537 newDir.setParentId(path.getFileId());
538 storageManager.saveFile(newDir);
539 return true;
540 } else {
541 return false;
542 }
543
544 }
545 return false;
546 }
547
548 private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType,
549 FileDataStorageManager storageManager) {
550 OCFile newFile = new OCFile(remotePath);
551 newFile.setStoragePath(localPath);
552 newFile.setLastSyncDateForProperties(0);
553 newFile.setLastSyncDateForData(0);
554
555 // size
556 if (localPath != null && localPath.length() > 0) {
557 File localFile = new File(localPath);
558 newFile.setFileLength(localFile.length());
559 newFile.setLastSyncDateForData(localFile.lastModified());
560 } // don't worry about not assigning size, the problems with localPath
561 // are checked when the UploadFileOperation instance is created
562
563 // MIME type
564 if (mimeType == null || mimeType.length() <= 0) {
565 try {
566 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
567 remotePath.substring(remotePath.lastIndexOf('.') + 1));
568 } catch (IndexOutOfBoundsException e) {
569 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
570 }
571 }
572 if (mimeType == null) {
573 mimeType = "application/octet-stream";
574 }
575 newFile.setMimetype(mimeType);
576
577 // parent dir
578 String parentPath = new File(remotePath).getParent();
579 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
580 OCFile parentDir = storageManager.getFileByPath(parentPath);
581 if (parentDir == null) {
582 Toast t = Toast
583 .makeText(
584 getApplicationContext(),
585 "The first time the InstantUpload is running you must be online, so the target folder can successfully created by the upload process",
586 30);
587 t.show();
588 return null;
589 }
590 long parentDirId = parentDir.getFileId();
591 newFile.setParentId(parentDirId);
592 return newFile;
593 }
594
595 /**
596 * Creates a status notification to show the upload progress
597 *
598 * @param upload Upload operation starting.
599 */
600 private void notifyUploadStart(UploadFileOperation upload) {
601 // / create status notification with a progress bar
602 mLastPercent = 0;
603 mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker),
604 System.currentTimeMillis());
605 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
606 mDefaultNotificationContentView = mNotification.contentView;
607 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(),
608 R.layout.progressbar_layout);
609 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
610 mNotification.contentView.setTextViewText(R.id.status_text,
611 String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
612 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
613
614 // / includes a pending intent in the notification showing the details
615 // view of the file
616 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
617 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
618 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
619 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
620 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
621 (int) System.currentTimeMillis(), showDetailsIntent, 0);
622
623 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
624 }
625
626 /**
627 * Callback method to update the progress bar in the status notification
628 */
629 @Override
630 public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
631 int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
632 if (percent != mLastPercent) {
633 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
634 String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
635 mNotification.contentView.setTextViewText(R.id.status_text, text);
636 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
637 }
638 mLastPercent = percent;
639 }
640
641 /**
642 * Callback method to update the progress bar in the status notification
643 * (old version)
644 */
645 @Override
646 public void onTransferProgress(long progressRate) {
647 // NOTHING TO DO HERE ANYMORE
648 }
649
650 /**
651 * Updates the status notification with the result of an upload operation.
652 *
653 * @param uploadResult Result of the upload operation.
654 * @param upload Finished upload operation
655 */
656 private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
657 Log.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
658 if (uploadResult.isCancelled()) {
659 // / cancelled operation -> silent removal of progress notification
660 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
661
662 } else if (uploadResult.isSuccess()) {
663 // / success -> silent update of progress notification to success
664 // message
665 mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove
666 // the
667 // ongoing
668 // flag
669 mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
670 mNotification.contentView = mDefaultNotificationContentView;
671
672 // / includes a pending intent in the notification showing the
673 // details view of the file
674 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
675 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
676 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
677 showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
678 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
679 (int) System.currentTimeMillis(), showDetailsIntent, 0);
680
681 mNotification.setLatestEventInfo(getApplicationContext(),
682 getString(R.string.uploader_upload_succeeded_ticker),
683 String.format(getString(R.string.uploader_upload_succeeded_content_single), upload.getFileName()),
684 mNotification.contentIntent);
685
686 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification); // NOT
687 // AN
688 DbHandler db = new DbHandler(this.getBaseContext());
689 db.removeIUPendingFile(mCurrentUpload.getFile().getStoragePath());
690 db.close();
691
692 } else {
693
694 // / fail -> explicit failure notification
695 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
696 Notification finalNotification = new Notification(R.drawable.icon,
697 getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
698 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
699
700 String content = null;
701 if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
702 || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
703 // TODO we need a class to provide error messages for the users
704 // from a RemoteOperationResult and a RemoteOperation
705 content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
706 getString(R.string.app_name));
707 } else if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
708 content = getString(R.string.failed_upload_quota_exceeded_text);
709 } else {
710 content = String
711 .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
712 }
713
714 // we add only for instant-uploads the InstantUploadActivity and the
715 // db entry
716 Intent detailUploadIntent = null;
717 if (upload.isInstant()) {
718 detailUploadIntent = new Intent(this, InstantUploadActivity.class);
719 detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
720 } else {
721 detailUploadIntent = new Intent(this, FailedUploadActivity.class);
722 detailUploadIntent.putExtra(FailedUploadActivity.MESSAGE, content);
723 }
724 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
725 (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT
726 | PendingIntent.FLAG_ONE_SHOT);
727
728 if (upload.isInstant()) {
729 DbHandler db = null;
730 try {
731 db = new DbHandler(this.getBaseContext());
732 String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
733 Log.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
734 if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
735 message = getString(R.string.failed_upload_quota_exceeded_text);
736 }
737 if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
738 message) == 0) {
739 db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message);
740 }
741 } finally {
742 if (db != null) {
743 db.close();
744 }
745 }
746 }
747 finalNotification.setLatestEventInfo(getApplicationContext(),
748 getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
749
750 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
751 }
752
753 }
754
755 /**
756 * Sends a broadcast in order to the interested activities can update their
757 * view
758 *
759 * @param upload Finished upload operation
760 * @param uploadResult Result of the upload operation
761 */
762 private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
763 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
764 end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
765 // path, after
766 // possible
767 // automatic
768 // renaming
769 if (upload.wasRenamed()) {
770 end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
771 }
772 end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
773 end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
774 end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
775 sendStickyBroadcast(end);
776 }
777
778 }