[tx-robot] updated from transifex
[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 public class FolderPickerActivity extends FileActivity implements FileFragment.ContainerActivity,
65 OnClickListener, OnEnforceableRefreshListener {
66
67 public static final String EXTRA_FOLDER = UploadFilesActivity.class.getCanonicalName()
68 + ".EXTRA_FOLDER";
69 public static final String EXTRA_FILE = UploadFilesActivity.class.getCanonicalName()
70 + ".EXTRA_FILE";
71 //TODO: Think something better
72
73 private SyncBroadcastReceiver mSyncBroadcastReceiver;
74
75 private static final String TAG = FolderPickerActivity.class.getSimpleName();
76
77 private static final String TAG_LIST_OF_FOLDERS = "LIST_OF_FOLDERS";
78
79 private boolean mSyncInProgress = false;
80
81 protected Button mCancelBtn;
82 protected Button mChooseBtn;
83 private ProgressBar mProgressBar;
84
85
86 @Override
87 protected void onCreate(Bundle savedInstanceState) {
88 Log_OC.d(TAG, "onCreate() start");
89
90 super.onCreate(savedInstanceState);
91
92 setContentView(R.layout.files_folder_picker);
93
94 if (savedInstanceState == null) {
95 createFragments();
96 }
97
98 // sets callback listeners for UI elements
99 initControls();
100
101 // Action bar setup
102 ActionBar actionBar = getSupportActionBar();
103 actionBar.setDisplayShowTitleEnabled(true);
104 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
105
106 mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
107 mProgressBar.setIndeterminateDrawable(
108 getResources().getDrawable(
109 R.drawable.actionbar_progress_indeterminate_horizontal));
110 mProgressBar.setIndeterminate(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 @Override
120 protected void onStart() {
121 super.onStart();
122 }
123
124 /**
125 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
126 */
127 @Override
128 protected void onAccountSet(boolean stateWasRecovered) {
129 super.onAccountSet(stateWasRecovered);
130 if (getAccount() != null) {
131
132 updateFileFromDB();
133
134 OCFile folder = getFile();
135 if (folder == null || !folder.isFolder()) {
136 // fall back to root folder
137 setFile(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
138 folder = getFile();
139 }
140
141 if (!stateWasRecovered) {
142 OCFileListFragment listOfFolders = getListOfFilesFragment();
143 listOfFolders.listDirectory(folder/*, false*/);
144
145 startSyncFolderOperation(folder, false);
146 }
147
148 updateNavigationElementsInActionBar();
149 }
150 }
151
152 private void createFragments() {
153 OCFileListFragment listOfFiles = new OCFileListFragment();
154 Bundle args = new Bundle();
155 args.putBoolean(OCFileListFragment.ARG_JUST_FOLDERS, true);
156 args.putBoolean(OCFileListFragment.ARG_ALLOW_CONTEXTUAL_ACTIONS, false);
157 listOfFiles.setArguments(args);
158 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
159 transaction.add(R.id.fragment_container, listOfFiles, TAG_LIST_OF_FOLDERS);
160 transaction.commit();
161 }
162
163 /**
164 * Show a text message on screen view for notifying user if content is
165 * loading or folder is empty
166 */
167 private void setBackgroundText() {
168 OCFileListFragment listFragment = getListOfFilesFragment();
169 if (listFragment != null) {
170 int message = R.string.file_list_loading;
171 if (!mSyncInProgress) {
172 // In case folder list is empty
173 message = R.string.file_list_empty_moving;
174 }
175 listFragment.setMessageForEmptyList(getString(message));
176 } else {
177 Log.e(TAG, "OCFileListFragment is null");
178 }
179 }
180
181 protected OCFileListFragment getListOfFilesFragment() {
182 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FolderPickerActivity.TAG_LIST_OF_FOLDERS);
183 if (listOfFiles != null) {
184 return (OCFileListFragment)listOfFiles;
185 }
186 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
187 return null;
188 }
189
190
191 /**
192 * {@inheritDoc}
193 *
194 * Updates action bar and second fragment, if in dual pane mode.
195 */
196 @Override
197 public void onBrowsedDownTo(OCFile directory) {
198 setFile(directory);
199 updateNavigationElementsInActionBar();
200 // Sync Folder
201 startSyncFolderOperation(directory, false);
202
203 }
204
205
206 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
207 long currentSyncTime = System.currentTimeMillis();
208
209 mSyncInProgress = true;
210
211 // perform folder synchronization
212 RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
213 currentSyncTime,
214 false,
215 getFileOperationsHelper().isSharedSupported(),
216 ignoreETag,
217 getStorageManager(),
218 getAccount(),
219 getApplicationContext()
220 );
221 synchFolderOp.execute(getAccount(), this, null, null);
222
223 mProgressBar.setIndeterminate(true);
224
225 setBackgroundText();
226 }
227
228 @Override
229 protected void onResume() {
230 super.onResume();
231 Log_OC.e(TAG, "onResume() start");
232
233 // refresh list of files
234 refreshListOfFilesFragment();
235
236 // Listen for sync messages
237 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
238 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
239 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
240 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
241 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
242 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
243 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
244
245 Log_OC.d(TAG, "onResume() end");
246 }
247
248 @Override
249 protected void onPause() {
250 Log_OC.e(TAG, "onPause() start");
251 if (mSyncBroadcastReceiver != null) {
252 unregisterReceiver(mSyncBroadcastReceiver);
253 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
254 mSyncBroadcastReceiver = null;
255 }
256
257 Log_OC.d(TAG, "onPause() end");
258 super.onPause();
259 }
260
261 @Override
262 public boolean onCreateOptionsMenu(Menu menu) {
263 MenuInflater inflater = getMenuInflater();
264 inflater.inflate(R.menu.main_menu, menu);
265 menu.findItem(R.id.action_upload).setVisible(false);
266 menu.findItem(R.id.action_sort).setVisible(false);
267 return true;
268 }
269
270 @Override
271 public boolean onOptionsItemSelected(MenuItem item) {
272 boolean retval = true;
273 switch (item.getItemId()) {
274 case R.id.action_create_dir: {
275 CreateFolderDialogFragment dialog =
276 CreateFolderDialogFragment.newInstance(getCurrentFolder());
277 dialog.show(
278 getSupportFragmentManager(),
279 CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT
280 );
281 break;
282 }
283 case android.R.id.home: {
284 OCFile currentDir = getCurrentFolder();
285 if(currentDir != null && currentDir.getParentId() != 0) {
286 onBackPressed();
287 }
288 break;
289 }
290 default:
291 retval = super.onOptionsItemSelected(item);
292 }
293 return retval;
294 }
295
296 protected OCFile getCurrentFolder() {
297 OCFile file = getFile();
298 if (file != null) {
299 if (file.isFolder()) {
300 return file;
301 } else if (getStorageManager() != null) {
302 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
303 return getStorageManager().getFileByPath(parentPath);
304 }
305 }
306 return null;
307 }
308
309 protected void refreshListOfFilesFragment() {
310 OCFileListFragment fileListFragment = getListOfFilesFragment();
311 if (fileListFragment != null) {
312 fileListFragment.listDirectory();
313 // TODO Enable when "On Device" is recovered ?
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);
323 // TODO Enable when "On Device" is recovered ?
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
376 Intent data = new Intent();
377 data.putExtra(EXTRA_FOLDER, getCurrentFolder());
378 if (targetFile != null) {
379 data.putExtra(EXTRA_FILE, targetFile);
380 }
381 setResult(RESULT_OK, data);
382 finish();
383 }
384 }
385
386
387 @Override
388 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
389 super.onRemoteOperationFinish(operation, result);
390
391 if (operation instanceof CreateFolderOperation) {
392 onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
393
394 }
395 }
396
397
398 /**
399 * Updates the view associated to the activity after the finish of an operation trying
400 * to create a new folder.
401 *
402 * @param operation Creation operation performed.
403 * @param result Result of the creation.
404 */
405 private void onCreateFolderOperationFinish(
406 CreateFolderOperation operation, RemoteOperationResult result
407 ) {
408
409 if (result.isSuccess()) {
410 refreshListOfFilesFragment();
411 } else {
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
526 mProgressBar.setIndeterminate(mSyncInProgress);
527
528 setBackgroundText();
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 }