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