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