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