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