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