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