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