6dec67d25c8dcde59442c03ea65ec4ed6fb91ead
[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 java.io.IOException;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.accounts.AuthenticatorException;
27 import android.accounts.OperationCanceledException;
28 import android.content.BroadcastReceiver;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.IntentFilter;
32 import android.content.res.Resources.NotFoundException;
33 import android.os.Bundle;
34 import android.os.Parcelable;
35 import android.support.v4.app.Fragment;
36 import android.support.v4.app.FragmentTransaction;
37 import android.util.Log;
38 import android.view.View;
39 import android.view.View.OnClickListener;
40 import android.widget.Button;
41 import android.widget.Toast;
42
43 import com.actionbarsherlock.app.ActionBar;
44 import com.actionbarsherlock.view.Menu;
45 import com.actionbarsherlock.view.MenuInflater;
46 import com.actionbarsherlock.view.MenuItem;
47 import com.actionbarsherlock.view.Window;
48 import com.owncloud.android.MainApp;
49 import com.owncloud.android.R;
50 import com.owncloud.android.datamodel.OCFile;
51 import com.owncloud.android.lib.common.OwnCloudAccount;
52 import com.owncloud.android.lib.common.OwnCloudClient;
53 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
54 import com.owncloud.android.lib.common.OwnCloudCredentials;
55 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
56 import com.owncloud.android.lib.common.operations.RemoteOperation;
57 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
58 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
59 import com.owncloud.android.lib.common.utils.Log_OC;
60 import com.owncloud.android.operations.CreateFolderOperation;
61 import com.owncloud.android.operations.RefreshFolderOperation;
62 import com.owncloud.android.syncadapter.FileSyncAdapter;
63 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
64 import com.owncloud.android.ui.fragment.FileFragment;
65 import com.owncloud.android.ui.fragment.OCFileListFragment;
66 import com.owncloud.android.utils.DisplayUtils;
67 import com.owncloud.android.utils.ErrorMessageAdapter;
68
69 public class FolderPickerActivity extends FileActivity implements FileFragment.ContainerActivity,
70 OnClickListener, OnEnforceableRefreshListener {
71
72 public static final String EXTRA_FOLDER = UploadFilesActivity.class.getCanonicalName()
73 + ".EXTRA_FOLDER";
74 public static final String EXTRA_FILE = UploadFilesActivity.class.getCanonicalName()
75 + ".EXTRA_FILE";
76 //TODO: Think something better
77
78 private SyncBroadcastReceiver mSyncBroadcastReceiver;
79
80 private static final String TAG = FolderPickerActivity.class.getSimpleName();
81
82 private static final String TAG_LIST_OF_FOLDERS = "LIST_OF_FOLDERS";
83
84 private boolean mSyncInProgress = false;
85
86 protected Button mCancelBtn;
87 protected Button mChooseBtn;
88
89
90 @Override
91 protected void onCreate(Bundle savedInstanceState) {
92 Log_OC.d(TAG, "onCreate() start");
93 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
94
95 super.onCreate(savedInstanceState);
96
97 setContentView(R.layout.files_folder_picker);
98
99 if (savedInstanceState == null) {
100 createFragments();
101 }
102
103 // sets callback listeners for UI elements
104 initControls();
105
106 // Action bar setup
107 ActionBar actionBar = getSupportActionBar();
108 actionBar.setDisplayShowTitleEnabled(true);
109 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
110 setSupportProgressBarIndeterminateVisibility(mSyncInProgress);
111 // always AFTER setContentView(...) ; to work around bug in its implementation
112
113 // sets message for empty list of folders
114 setBackgroundText();
115
116 Log_OC.d(TAG, "onCreate() end");
117
118 }
119
120 @Override
121 protected void onStart() {
122 super.onStart();
123 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
124 }
125
126 /**
127 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
128 */
129 @Override
130 protected void onAccountSet(boolean stateWasRecovered) {
131 super.onAccountSet(stateWasRecovered);
132 if (getAccount() != null) {
133
134 updateFileFromDB();
135
136 OCFile folder = getFile();
137 if (folder == null || !folder.isFolder()) {
138 // fall back to root folder
139 setFile(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
140 folder = getFile();
141 }
142
143 if (!stateWasRecovered) {
144 OCFileListFragment listOfFolders = getListOfFilesFragment();
145 listOfFolders.listDirectory(folder, false);
146
147 startSyncFolderOperation(folder, false);
148 }
149
150 updateNavigationElementsInActionBar();
151 }
152 }
153
154 private void createFragments() {
155 OCFileListFragment listOfFiles = new OCFileListFragment();
156 Bundle args = new Bundle();
157 args.putBoolean(OCFileListFragment.ARG_JUST_FOLDERS, true);
158 args.putBoolean(OCFileListFragment.ARG_ALLOW_CONTEXTUAL_ACTIONS, false);
159 listOfFiles.setArguments(args);
160 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
161 transaction.add(R.id.fragment_container, listOfFiles, TAG_LIST_OF_FOLDERS);
162 transaction.commit();
163 }
164
165 /**
166 * Show a text message on screen view for notifying user if content is
167 * loading or folder is empty
168 */
169 private void setBackgroundText() {
170 OCFileListFragment listFragment = getListOfFilesFragment();
171 if (listFragment != null) {
172 int message = R.string.file_list_loading;
173 if (!mSyncInProgress) {
174 // In case folder list is empty
175 message = R.string.file_list_empty_moving;
176 }
177 listFragment.setMessageForEmptyList(getString(message));
178 } else {
179 Log.e(TAG, "OCFileListFragment is null");
180 }
181 }
182
183 protected OCFileListFragment getListOfFilesFragment() {
184 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FolderPickerActivity.TAG_LIST_OF_FOLDERS);
185 if (listOfFiles != null) {
186 return (OCFileListFragment)listOfFiles;
187 }
188 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
189 return null;
190 }
191
192
193 /**
194 * {@inheritDoc}
195 *
196 * Updates action bar and second fragment, if in dual pane mode.
197 */
198 @Override
199 public void onBrowsedDownTo(OCFile directory) {
200 setFile(directory);
201 updateNavigationElementsInActionBar();
202 // Sync Folder
203 startSyncFolderOperation(directory, false);
204
205 }
206
207
208 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
209 long currentSyncTime = System.currentTimeMillis();
210
211 mSyncInProgress = true;
212
213 // perform folder synchronization
214 RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
215 currentSyncTime,
216 false,
217 getFileOperationsHelper().isSharedSupported(),
218 ignoreETag,
219 getStorageManager(),
220 getAccount(),
221 getApplicationContext()
222 );
223 synchFolderOp.execute(getAccount(), this, null, null);
224
225 setSupportProgressBarIndeterminateVisibility(true);
226
227 setBackgroundText();
228 }
229
230 @Override
231 protected void onResume() {
232 super.onResume();
233 Log_OC.e(TAG, "onResume() start");
234
235 // refresh list of files
236 refreshListOfFilesFragment();
237
238 // Listen for sync messages
239 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
240 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
241 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
242 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
243 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
244 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
245 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
246
247 Log_OC.d(TAG, "onResume() end");
248 }
249
250 @Override
251 protected void onPause() {
252 Log_OC.e(TAG, "onPause() start");
253 if (mSyncBroadcastReceiver != null) {
254 unregisterReceiver(mSyncBroadcastReceiver);
255 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
256 mSyncBroadcastReceiver = null;
257 }
258
259 Log_OC.d(TAG, "onPause() end");
260 super.onPause();
261 }
262
263 @Override
264 public boolean onCreateOptionsMenu(Menu menu) {
265 MenuInflater inflater = getSherlock().getMenuInflater();
266 inflater.inflate(R.menu.main_menu, menu);
267 menu.findItem(R.id.action_upload).setVisible(false);
268 menu.findItem(R.id.action_sort).setVisible(false);
269 return true;
270 }
271
272 @Override
273 public boolean onOptionsItemSelected(MenuItem item) {
274 boolean retval = true;
275 switch (item.getItemId()) {
276 case R.id.action_create_dir: {
277 CreateFolderDialogFragment dialog =
278 CreateFolderDialogFragment.newInstance(getCurrentFolder());
279 dialog.show(
280 getSupportFragmentManager(),
281 CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT
282 );
283 break;
284 }
285 case android.R.id.home: {
286 OCFile currentDir = getCurrentFolder();
287 if(currentDir != null && currentDir.getParentId() != 0) {
288 onBackPressed();
289 }
290 break;
291 }
292 default:
293 retval = super.onOptionsItemSelected(item);
294 }
295 return retval;
296 }
297
298 protected OCFile getCurrentFolder() {
299 OCFile file = getFile();
300 if (file != null) {
301 if (file.isFolder()) {
302 return file;
303 } else if (getStorageManager() != null) {
304 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
305 return getStorageManager().getFileByPath(parentPath);
306 }
307 }
308 return null;
309 }
310
311 protected void refreshListOfFilesFragment() {
312 OCFileListFragment fileListFragment = getListOfFilesFragment();
313 if (fileListFragment != null) {
314 fileListFragment.listDirectory(false);
315 }
316 }
317
318 public void browseToRoot() {
319 OCFileListFragment listOfFiles = getListOfFilesFragment();
320 if (listOfFiles != null) { // should never be null, indeed
321 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
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, false);
475 }
476 }
477 setFile(currentFile);
478 }
479
480 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
481 !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
482
483 if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
484 equals(event) &&
485 /// TODO refactor and make common
486 synchResult != null && !synchResult.isSuccess() &&
487 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
488 synchResult.isIdPRedirection() ||
489 (synchResult.isException() && synchResult.getException()
490 instanceof AuthenticatorException))) {
491
492 try {
493 OwnCloudClient client;
494 OwnCloudAccount ocAccount =
495 new OwnCloudAccount(getAccount(), context);
496 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
497 removeClientFor(ocAccount));
498
499 if (client != null) {
500 OwnCloudCredentials cred = client.getCredentials();
501 if (cred != null) {
502 AccountManager am = AccountManager.get(context);
503 if (cred.authTokenExpires()) {
504 am.invalidateAuthToken(
505 getAccount().type,
506 cred.getAuthToken()
507 );
508 } else {
509 am.clearPassword(getAccount());
510 }
511 }
512 }
513 requestCredentialsUpdate();
514
515 } catch (AccountNotFoundException e) {
516 Log_OC.e(TAG, "Account " + getAccount() + " was removed!", e);
517 }
518
519 }
520 }
521 removeStickyBroadcast(intent);
522 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
523 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
524
525 setBackgroundText();
526
527 }
528
529 } catch (RuntimeException e) {
530 // avoid app crashes after changing the serial id of RemoteOperationResult
531 // in owncloud library with broadcast notifications pending to process
532 removeStickyBroadcast(intent);
533 }
534 }
535 }
536
537
538
539 /**
540 * Shows the information of the {@link OCFile} received as a
541 * parameter in the second fragment.
542 *
543 * @param file {@link OCFile} whose details will be shown
544 */
545 @Override
546 public void showDetails(OCFile file) {
547
548 }
549
550 /**
551 * {@inheritDoc}
552 */
553 @Override
554 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
555
556 }
557
558 @Override
559 public void onRefresh() {
560 refreshList(true);
561 }
562
563 @Override
564 public void onRefresh(boolean enforced) {
565 refreshList(enforced);
566 }
567
568 private void refreshList(boolean ignoreETag) {
569 OCFileListFragment listOfFiles = getListOfFilesFragment();
570 if (listOfFiles != null) {
571 OCFile folder = listOfFiles.getCurrentFile();
572 if (folder != null) {
573 startSyncFolderOperation(folder, ignoreETag);
574 }
575 }
576 }
577 }