Added copy action
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / CopyActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.ui.activity;
19
20 import android.accounts.Account;
21 import android.accounts.AccountManager;
22 import android.accounts.AuthenticatorException;
23 import android.content.BroadcastReceiver;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.IntentFilter;
27 import android.content.res.Resources.NotFoundException;
28 import android.os.Bundle;
29 import android.support.v4.app.Fragment;
30 import android.support.v4.app.FragmentTransaction;
31 import android.support.v4.widget.SwipeRefreshLayout;
32 import android.support.v7.app.ActionBar;
33 import android.util.Log;
34 import android.view.Menu;
35 import android.view.MenuInflater;
36 import android.view.MenuItem;
37 import android.view.View;
38 import android.view.View.OnClickListener;
39 import android.view.Window;
40 import android.widget.Button;
41 import android.widget.Toast;
42
43 import com.owncloud.android.R;
44 import com.owncloud.android.datamodel.OCFile;
45 import com.owncloud.android.lib.common.OwnCloudAccount;
46 import com.owncloud.android.lib.common.OwnCloudClient;
47 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
48 import com.owncloud.android.lib.common.OwnCloudCredentials;
49 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
50 import com.owncloud.android.lib.common.operations.RemoteOperation;
51 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
52 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
53 import com.owncloud.android.lib.common.utils.Log_OC;
54 import com.owncloud.android.operations.CreateFolderOperation;
55 import com.owncloud.android.operations.RefreshFolderOperation;
56 import com.owncloud.android.syncadapter.FileSyncAdapter;
57 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
58 import com.owncloud.android.ui.fragment.FileFragment;
59 import com.owncloud.android.ui.fragment.OCFileListFragment;
60 import com.owncloud.android.utils.DisplayUtils;
61 import com.owncloud.android.utils.ErrorMessageAdapter;
62
63 public class CopyActivity extends HookActivity implements FileFragment.ContainerActivity,
64 OnClickListener, SwipeRefreshLayout.OnRefreshListener {
65
66 public static final String EXTRA_CURRENT_FOLDER = UploadFilesActivity.class.getCanonicalName() + ".EXTRA_CURRENT_FOLDER";
67 public static final String EXTRA_TARGET_FILE = UploadFilesActivity.class.getCanonicalName() + "EXTRA_TARGET_FILE";
68
69 public static final int RESULT_OK_AND_COPY = 1;
70
71 private SyncBroadcastReceiver mSyncBroadcastReceiver;
72
73 private static final String TAG = CopyActivity.class.getSimpleName();
74
75 private static final String TAG_LIST_OF_FOLDERS = "LIST_OF_FOLDERS";
76
77 private boolean mSyncInProgress = false;
78
79 private Button mCancelBtn;
80 private Button mChooseBtn;
81
82
83 @Override
84 protected void onCreate(Bundle savedInstanceState) {
85 Log_OC.d(TAG, "onCreate() start");
86 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
87
88 super.onCreate(savedInstanceState);
89
90 setContentView(R.layout.files_folder_picker);
91
92 if (savedInstanceState == null) {
93 createFragments();
94 }
95
96 // sets callback listeners for UI elements
97 initControls();
98
99 // Action bar setup
100 ActionBar actionBar = getSupportActionBar();
101 actionBar.setDisplayShowTitleEnabled(true);
102 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
103 setSupportProgressBarIndeterminateVisibility(mSyncInProgress);
104 // always AFTER setContentView(...) ; to work around bug in its implementation
105
106 // sets message for empty list of folders
107 setBackgroundText();
108
109 Log_OC.d(TAG, "onCreate() end");
110
111 }
112
113 @Override
114 protected void onStart() {
115 super.onStart();
116 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
117 }
118
119 @Override
120 protected void onDestroy() {
121 super.onDestroy();
122 }
123
124 /**
125 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
126 */
127 @Override
128 protected void onAccountSet(boolean stateWasRecovered) {
129 super.onAccountSet(stateWasRecovered);
130 if (getAccount() != null) {
131
132 updateFileFromDB();
133
134 OCFile folder = getFile();
135 if (folder == null || !folder.isFolder()) {
136 // fall back to root folder
137 setFile(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
138 folder = getFile();
139 }
140
141 if (!stateWasRecovered) {
142 OCFileListFragment listOfFolders = getListOfFilesFragment();
143 listOfFolders.listDirectory(folder);
144
145 startSyncFolderOperation(folder, false);
146 }
147
148 updateNavigationElementsInActionBar();
149 }
150 }
151
152 private void createFragments() {
153 OCFileListFragment listOfFiles = new OCFileListFragment();
154 Bundle args = new Bundle();
155 args.putBoolean(OCFileListFragment.ARG_JUST_FOLDERS, true);
156 args.putBoolean(OCFileListFragment.ARG_ALLOW_CONTEXTUAL_ACTIONS, false);
157 listOfFiles.setArguments(args);
158 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
159 transaction.add(R.id.fragment_container, listOfFiles, TAG_LIST_OF_FOLDERS);
160 transaction.commit();
161 }
162
163 /**
164 * Show a text message on screen view for notifying user if content is
165 * loading or folder is empty
166 */
167 private void setBackgroundText() {
168 OCFileListFragment listFragment = getListOfFilesFragment();
169 if (listFragment != null) {
170 int message = R.string.file_list_loading;
171 if (!mSyncInProgress) {
172 // In case folder list is empty
173 message = R.string.file_list_empty_moving;
174 }
175 listFragment.setMessageForEmptyList(getString(message));
176 } else {
177 Log.e(TAG, "OCFileListFragment is null");
178 }
179 }
180
181 private OCFileListFragment getListOfFilesFragment() {
182 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(CopyActivity.TAG_LIST_OF_FOLDERS);
183 if (listOfFiles != null) {
184 return (OCFileListFragment) listOfFiles;
185 }
186 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
187 return null;
188 }
189
190
191 /**
192 * {@inheritDoc}
193 * <p/>
194 * Updates action bar and second fragment, if in dual pane mode.
195 */
196 @Override
197 public void onBrowsedDownTo(OCFile directory) {
198 setFile(directory);
199 updateNavigationElementsInActionBar();
200 // Sync Folder
201 startSyncFolderOperation(directory, false);
202
203 }
204
205
206 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
207 long currentSyncTime = System.currentTimeMillis();
208
209 mSyncInProgress = true;
210
211 // perform folder synchronization
212 RemoteOperation synchFolderOp = new RefreshFolderOperation(folder,
213 currentSyncTime,
214 false,
215 getFileOperationsHelper().isSharedSupported(),
216 ignoreETag,
217 getStorageManager(),
218 getAccount(),
219 getApplicationContext()
220 );
221 synchFolderOp.execute(getAccount(), this, null, null);
222
223 setSupportProgressBarIndeterminateVisibility(true);
224
225 setBackgroundText();
226 }
227
228 @Override
229 protected void onResume() {
230 super.onResume();
231 Log_OC.e(TAG, "onResume() start");
232
233 // refresh list of files
234 refreshListOfFilesFragment();
235
236 // Listen for sync messages
237 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
238 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
239 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
240 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
241 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
242 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
243 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
244
245 Log_OC.d(TAG, "onResume() end");
246 }
247
248 @Override
249 protected void onPause() {
250 Log_OC.e(TAG, "onPause() start");
251 if (mSyncBroadcastReceiver != null) {
252 unregisterReceiver(mSyncBroadcastReceiver);
253 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
254 mSyncBroadcastReceiver = null;
255 }
256
257 Log_OC.d(TAG, "onPause() end");
258 super.onPause();
259 }
260
261 @Override
262 public boolean onCreateOptionsMenu(Menu menu) {
263 MenuInflater inflater = getMenuInflater();
264 inflater.inflate(R.menu.main_menu, menu);
265 menu.findItem(R.id.action_upload).setVisible(false);
266 menu.findItem(R.id.action_sync_account).setVisible(false);
267 return true;
268 }
269
270 @Override
271 public boolean onOptionsItemSelected(MenuItem item) {
272 boolean retval = true;
273 switch (item.getItemId()) {
274 case R.id.action_create_dir: {
275 CreateFolderDialogFragment dialog =
276 CreateFolderDialogFragment.newInstance(getCurrentFolder());
277 dialog.show(
278 getSupportFragmentManager(),
279 CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT
280 );
281 break;
282 }
283 case android.R.id.home: {
284 OCFile currentDir = getCurrentFolder();
285 if (currentDir != null && currentDir.getParentId() != 0) {
286 onBackPressed();
287 }
288 break;
289 }
290 default:
291 retval = super.onOptionsItemSelected(item);
292 }
293 return retval;
294 }
295
296 private OCFile getCurrentFolder() {
297 OCFile file = getFile();
298 if (file != null) {
299 if (file.isFolder()) {
300 return file;
301 } else if (getStorageManager() != null) {
302 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
303 return getStorageManager().getFileByPath(parentPath);
304 }
305 }
306 return null;
307 }
308
309 protected void refreshListOfFilesFragment() {
310 OCFileListFragment fileListFragment = getListOfFilesFragment();
311 if (fileListFragment != null) {
312 fileListFragment.listDirectory();
313 }
314 }
315
316 public void browseToRoot() {
317 OCFileListFragment listOfFiles = getListOfFilesFragment();
318 if (listOfFiles != null) { // should never be null, indeed
319 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
320 listOfFiles.listDirectory(root);
321 setFile(listOfFiles.getCurrentFile());
322 updateNavigationElementsInActionBar();
323 startSyncFolderOperation(root, false);
324 }
325 }
326
327 @Override
328 public void onBackPressed() {
329 OCFileListFragment listOfFiles = getListOfFilesFragment();
330 if (listOfFiles != null) { // should never be null, indeed
331 int levelsUp = listOfFiles.onBrowseUp();
332 if (levelsUp == 0) {
333 finish();
334 return;
335 }
336 setFile(listOfFiles.getCurrentFile());
337 updateNavigationElementsInActionBar();
338 }
339 }
340
341 private void updateNavigationElementsInActionBar() {
342 ActionBar actionBar = getSupportActionBar();
343 OCFile currentDir = getCurrentFolder();
344 boolean atRoot = (currentDir == null || currentDir.getParentId() == 0);
345 actionBar.setDisplayHomeAsUpEnabled(!atRoot);
346 actionBar.setHomeButtonEnabled(!atRoot);
347 actionBar.setTitle(
348 atRoot
349 ? getString(R.string.default_display_name_for_root_folder)
350 : currentDir.getFileName()
351 );
352 }
353
354 /**
355 * Set per-view controllers
356 */
357 private void initControls() {
358 mCancelBtn = (Button) findViewById(R.id.folder_picker_btn_cancel);
359 mCancelBtn.setOnClickListener(this);
360 mChooseBtn = (Button) findViewById(R.id.folder_picker_btn_choose);
361 mChooseBtn.setOnClickListener(this);
362 }
363
364 @Override
365 public void onClick(View v) {
366 if (v == mCancelBtn) {
367 finish();
368 } else if (v == mChooseBtn) {
369 Intent i = getIntent();
370 OCFile targetFile = i.getParcelableExtra(CopyActivity.EXTRA_TARGET_FILE);
371
372 Intent data = new Intent();
373 data.putExtra(EXTRA_CURRENT_FOLDER, getCurrentFolder());
374 data.putExtra(EXTRA_TARGET_FILE, targetFile);
375 setResult(RESULT_OK_AND_COPY, data);
376 finish();
377 }
378 }
379
380
381 @Override
382 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
383 super.onRemoteOperationFinish(operation, result);
384
385 if (operation instanceof CreateFolderOperation) {
386 onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
387
388 }
389 }
390
391
392 /**
393 * Updates the view associated to the activity after the finish of an operation trying
394 * to create a new folder.
395 *
396 * @param operation Creation operation performed.
397 * @param result Result of the creation.
398 */
399 private void onCreateFolderOperationFinish(
400 CreateFolderOperation operation, RemoteOperationResult result
401 ) {
402
403 if (result.isSuccess()) {
404 dismissLoadingDialog();
405 refreshListOfFilesFragment();
406 } else {
407 dismissLoadingDialog();
408 try {
409 Toast msg = Toast.makeText(CopyActivity.this,
410 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
411 Toast.LENGTH_LONG);
412 msg.show();
413
414 } catch (NotFoundException e) {
415 Log_OC.e(TAG, "Error while trying to show fail message ", e);
416 }
417 }
418 }
419
420
421 private class SyncBroadcastReceiver extends BroadcastReceiver {
422
423 /**
424 * {@link BroadcastReceiver} to enable syncing feedback in UI
425 */
426 @Override
427 public void onReceive(Context context, Intent intent) {
428 try {
429 String event = intent.getAction();
430 Log_OC.d(TAG, "Received broadcast " + event);
431 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
432 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
433 RemoteOperationResult synchResult = (RemoteOperationResult) intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
434 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
435
436 if (sameAccount) {
437
438 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
439 mSyncInProgress = true;
440
441 } else {
442 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
443 OCFile currentDir = (getCurrentFolder() == null) ? null : getStorageManager().getFileByPath(getCurrentFolder().getRemotePath());
444
445 if (currentDir == null) {
446 // current folder was removed from the server
447 Toast.makeText(CopyActivity.this,
448 String.format(getString(R.string.sync_current_folder_was_removed), getCurrentFolder().getFileName()),
449 Toast.LENGTH_LONG)
450 .show();
451 browseToRoot();
452
453 } else {
454 if (currentFile == null && !getFile().isFolder()) {
455 // currently selected file was removed in the server, and now we know it
456 currentFile = currentDir;
457 }
458
459 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
460 OCFileListFragment fileListFragment = getListOfFilesFragment();
461 if (fileListFragment != null) {
462 fileListFragment.listDirectory(currentDir);
463 }
464 }
465 setFile(currentFile);
466 }
467
468 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
469
470 if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
471 equals(event) &&
472 /// TODO refactor and make common
473 synchResult != null && !synchResult.isSuccess() &&
474 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
475 synchResult.isIdPRedirection() ||
476 (synchResult.isException() && synchResult.getException()
477 instanceof AuthenticatorException))) {
478
479 try {
480 OwnCloudClient client;
481 OwnCloudAccount ocAccount =
482 new OwnCloudAccount(getAccount(), context);
483 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
484 removeClientFor(ocAccount));
485
486 if (client != null) {
487 OwnCloudCredentials cred = client.getCredentials();
488 if (cred != null) {
489 AccountManager am = AccountManager.get(context);
490 if (cred.authTokenExpires()) {
491 am.invalidateAuthToken(
492 getAccount().type,
493 cred.getAuthToken()
494 );
495 } else {
496 am.clearPassword(getAccount());
497 }
498 }
499 }
500 requestCredentialsUpdate();
501
502 } catch (AccountNotFoundException e) {
503 Log_OC.e(TAG, "Account " + getAccount() + " was removed!", e);
504 }
505
506 }
507 }
508 removeStickyBroadcast(intent);
509 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
510 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
511
512 setBackgroundText();
513
514 }
515
516 } catch (RuntimeException e) {
517 // avoid app crashes after changing the serial id of RemoteOperationResult
518 // in owncloud library with broadcast notifications pending to process
519 removeStickyBroadcast(intent);
520 }
521 }
522 }
523
524
525 /**
526 * Shows the information of the {@link OCFile} received as a
527 * parameter in the second fragment.
528 *
529 * @param file {@link OCFile} whose details will be shown
530 */
531 @Override
532 public void showDetails(OCFile file) {
533
534 }
535
536 /**
537 * {@inheritDoc}
538 */
539 @Override
540 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
541
542 }
543
544
545 @Override
546 public void onRefresh() {
547 OCFileListFragment listOfFiles = getListOfFilesFragment();
548 if (listOfFiles != null) {
549 OCFile folder = listOfFiles.getCurrentFile();
550 if (folder != null) {
551 startSyncFolderOperation(folder, true);
552 }
553 }
554 }
555
556 }