Merge branch 'develop' into accessibility
[pub/Android/ownCloud.git] / src / com / owncloud / android / services / SyncFolderHandler.java
1 /**
2 * ownCloud Android client application
3 *
4 * Copyright (C) 2015 ownCloud Inc.
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2,
8 * as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20 package com.owncloud.android.services;
21
22 import android.accounts.Account;
23 import android.accounts.AccountsException;
24 import android.content.Intent;
25 import android.os.Handler;
26 import android.os.Looper;
27 import android.os.Message;
28 import android.util.Pair;
29
30 import com.owncloud.android.datamodel.FileDataStorageManager;
31 import com.owncloud.android.datamodel.OCFile;
32 import com.owncloud.android.files.services.FileDownloader;
33 import com.owncloud.android.files.services.IndexedForest;
34 import com.owncloud.android.lib.common.OwnCloudAccount;
35 import com.owncloud.android.lib.common.OwnCloudClient;
36 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
37 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
38 import com.owncloud.android.lib.common.utils.Log_OC;
39 import com.owncloud.android.operations.SynchronizeFolderOperation;
40 import com.owncloud.android.utils.FileStorageUtils;
41
42 import java.io.IOException;
43
44 /**
45 * SyncFolder worker. Performs the pending operations in the order they were requested.
46 *
47 * Created with the Looper of a new thread, started in
48 * {@link com.owncloud.android.services.OperationsService#onCreate()}.
49 */
50 class SyncFolderHandler extends Handler {
51
52 private static final String TAG = SyncFolderHandler.class.getSimpleName();
53
54
55 OperationsService mService;
56
57 private IndexedForest<SynchronizeFolderOperation> mPendingOperations =
58 new IndexedForest<SynchronizeFolderOperation>();
59
60 private OwnCloudClient mOwnCloudClient = null;
61 private Account mCurrentAccount = null;
62 private FileDataStorageManager mStorageManager;
63 private SynchronizeFolderOperation mCurrentSyncOperation;
64
65
66 public SyncFolderHandler(Looper looper, OperationsService service) {
67 super(looper);
68 if (service == null) {
69 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
70 }
71 mService = service;
72 }
73
74
75 /**
76 * Returns True when the folder located in 'remotePath' in the ownCloud account 'account', or any of its
77 * descendants, is being synchronized (or waiting for it).
78 *
79 * @param account ownCloud account where the remote folder is stored.
80 * @param remotePath The path to a folder that could be in the queue of synchronizations.
81 */
82 public boolean isSynchronizing(Account account, String remotePath) {
83 if (account == null || remotePath == null) return false;
84 return (mPendingOperations.contains(account, remotePath));
85 }
86
87
88 @Override
89 public void handleMessage(Message msg) {
90 Pair<Account, String> itemSyncKey = (Pair<Account, String>) msg.obj;
91 doOperation(itemSyncKey.first, itemSyncKey.second);
92 Log_OC.d(TAG, "Stopping after command with id " + msg.arg1);
93 mService.stopSelf(msg.arg1);
94 }
95
96
97 /**
98 * Performs the next operation in the queue
99 */
100 private void doOperation(Account account, String remotePath) {
101
102 mCurrentSyncOperation = mPendingOperations.get(account, remotePath);
103
104 if (mCurrentSyncOperation != null) {
105 RemoteOperationResult result = null;
106
107 try {
108
109 if (mCurrentAccount == null || !mCurrentAccount.equals(account)) {
110 mCurrentAccount = account;
111 mStorageManager = new FileDataStorageManager(
112 account,
113 mService.getContentResolver()
114 );
115 } // else, reuse storage manager from previous operation
116
117 // always get client from client manager, to get fresh credentials in case of update
118 OwnCloudAccount ocAccount = new OwnCloudAccount(account, mService);
119 mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().
120 getClientFor(ocAccount, mService);
121
122 result = mCurrentSyncOperation.execute(mOwnCloudClient, mStorageManager);
123
124 } catch (AccountsException e) {
125 Log_OC.e(TAG, "Error while trying to get authorization", e);
126 } catch (IOException e) {
127 Log_OC.e(TAG, "Error while trying to get authorization", e);
128 } finally {
129 mPendingOperations.removePayload(account, remotePath);
130
131 mService.dispatchResultToOperationListeners(mCurrentSyncOperation, result);
132
133 sendBroadcastFinishedSyncFolder(account, remotePath, result.isSuccess());
134 }
135 }
136 }
137
138 public void add(Account account, String remotePath, SynchronizeFolderOperation syncFolderOperation){
139 mPendingOperations.putIfAbsent(account, remotePath, syncFolderOperation);
140 sendBroadcastNewSyncFolder(account, remotePath); // TODO upgrade!
141 }
142
143
144 /**
145 * Cancels a pending or current sync' operation.
146 *
147 * @param account ownCloud account where the remote file is stored.
148 * @param file A file in the queue of pending synchronizations
149 */
150 public void cancel(Account account, OCFile file){
151 if (account == null || file == null) {
152 Log_OC.e(TAG, "Cannot cancel with NULL parameters");
153 return;
154 }
155 Pair<SynchronizeFolderOperation, String> removeResult =
156 mPendingOperations.remove(account, file.getRemotePath());
157 SynchronizeFolderOperation synchronization = removeResult.first;
158 if (synchronization != null) {
159 synchronization.cancel();
160 } else {
161 // TODO synchronize?
162 if (mCurrentSyncOperation != null && mCurrentAccount != null &&
163 mCurrentSyncOperation.getRemotePath().startsWith(file.getRemotePath()) &&
164 account.name.equals(mCurrentAccount.name)) {
165 mCurrentSyncOperation.cancel();
166 }
167 }
168
169 //sendBroadcastFinishedSyncFolder(account, file.getRemotePath());
170 }
171
172 /**
173 * TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly
174 * patch.
175 */
176 private void sendBroadcastNewSyncFolder(Account account, String remotePath) {
177 Intent added = new Intent(FileDownloader.getDownloadAddedMessage());
178 added.putExtra(FileDownloader.ACCOUNT_NAME, account.name);
179 added.putExtra(FileDownloader.EXTRA_REMOTE_PATH, remotePath);
180 added.putExtra(FileDownloader.EXTRA_FILE_PATH, FileStorageUtils.getSavePath(account.name) + remotePath);
181 mService.sendStickyBroadcast(added);
182 }
183
184 /**
185 * TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly
186 * patch.
187 */
188 private void sendBroadcastFinishedSyncFolder(Account account, String remotePath, boolean success) {
189 Intent finished = new Intent(FileDownloader.getDownloadFinishMessage());
190 finished.putExtra(FileDownloader.ACCOUNT_NAME, account.name);
191 finished.putExtra(FileDownloader.EXTRA_REMOTE_PATH, remotePath);
192 finished.putExtra(FileDownloader.EXTRA_FILE_PATH, FileStorageUtils.getSavePath(account.name) + remotePath);
193 finished.putExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, success);
194 mService.sendStickyBroadcast(finished);
195 }
196
197
198 }