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