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