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