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