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