FolderPickerActivity.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * Copyright (C) 2016 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. package com.owncloud.android.ui.activity;
  20. import android.accounts.Account;
  21. import android.accounts.AuthenticatorException;
  22. import android.content.BroadcastReceiver;
  23. import android.content.Context;
  24. import android.content.Intent;
  25. import android.content.IntentFilter;
  26. import android.content.res.Resources.NotFoundException;
  27. import android.os.Bundle;
  28. import android.os.Parcelable;
  29. import android.support.v4.app.Fragment;
  30. import android.support.v4.app.FragmentTransaction;
  31. import android.support.v7.app.ActionBar;
  32. import android.util.Log;
  33. import android.view.Menu;
  34. import android.view.MenuInflater;
  35. import android.view.MenuItem;
  36. import android.view.View;
  37. import android.view.View.OnClickListener;
  38. import android.widget.Button;
  39. import android.widget.ProgressBar;
  40. import android.widget.Toast;
  41. import com.owncloud.android.R;
  42. import com.owncloud.android.datamodel.OCFile;
  43. import com.owncloud.android.lib.common.operations.RemoteOperation;
  44. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  45. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  46. import com.owncloud.android.lib.common.utils.Log_OC;
  47. import com.owncloud.android.operations.CreateFolderOperation;
  48. import com.owncloud.android.operations.RefreshFolderOperation;
  49. import com.owncloud.android.syncadapter.FileSyncAdapter;
  50. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  51. import com.owncloud.android.ui.fragment.FileFragment;
  52. import com.owncloud.android.ui.fragment.OCFileListFragment;
  53. import com.owncloud.android.utils.ErrorMessageAdapter;
  54. import java.util.ArrayList;
  55. public class FolderPickerActivity extends FileActivity implements FileFragment.ContainerActivity,
  56. OnClickListener, OnEnforceableRefreshListener {
  57. public static final String EXTRA_FOLDER = FolderPickerActivity.class.getCanonicalName()
  58. + ".EXTRA_FOLDER";
  59. public static final String EXTRA_FILES = FolderPickerActivity.class.getCanonicalName()
  60. + ".EXTRA_FILES";
  61. public static final String EXTRA_ACTION = FolderPickerActivity.class.getCanonicalName()
  62. + ".EXTRA_ACTION";
  63. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  64. private static final String TAG = FolderPickerActivity.class.getSimpleName();
  65. private static final String TAG_LIST_OF_FOLDERS = "LIST_OF_FOLDERS";
  66. private boolean mSyncInProgress = false;
  67. protected Button mCancelBtn;
  68. protected Button mChooseBtn;
  69. private String caption;
  70. @Override
  71. protected void onCreate(Bundle savedInstanceState) {
  72. Log_OC.d(TAG, "onCreate() start");
  73. super.onCreate(savedInstanceState);
  74. setContentView(R.layout.files_folder_picker);
  75. if (savedInstanceState == null) {
  76. createFragments();
  77. }
  78. // sets callback listeners for UI elements
  79. initControls();
  80. // Action bar setup
  81. setupToolbar();
  82. getSupportActionBar().setDisplayShowTitleEnabled(true);
  83. if (getIntent().getStringExtra(EXTRA_ACTION) != null) {
  84. caption = getIntent().getStringExtra(EXTRA_ACTION);
  85. } else {
  86. caption = getString(R.string.default_display_name_for_root_folder);
  87. };
  88. getSupportActionBar().setTitle(caption);
  89. setIndeterminate(mSyncInProgress);
  90. // always AFTER setContentView(...) ; to work around bug in its implementation
  91. // sets message for empty list of folders
  92. setBackgroundText();
  93. Log_OC.d(TAG, "onCreate() end");
  94. }
  95. @Override
  96. protected void onStart() {
  97. super.onStart();
  98. }
  99. /**
  100. * Called when the ownCloud {@link Account} associated to the Activity was just updated.
  101. */
  102. @Override
  103. protected void onAccountSet(boolean stateWasRecovered) {
  104. super.onAccountSet(stateWasRecovered);
  105. if (getAccount() != null) {
  106. updateFileFromDB();
  107. OCFile folder = getFile();
  108. if (folder == null || !folder.isFolder()) {
  109. // fall back to root folder
  110. setFile(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
  111. folder = getFile();
  112. }
  113. if (!stateWasRecovered) {
  114. OCFileListFragment listOfFolders = getListOfFilesFragment();
  115. listOfFolders.listDirectory(folder, false);
  116. startSyncFolderOperation(folder, false);
  117. }
  118. updateNavigationElementsInActionBar();
  119. }
  120. }
  121. private void createFragments() {
  122. OCFileListFragment listOfFiles = new OCFileListFragment();
  123. Bundle args = new Bundle();
  124. args.putBoolean(OCFileListFragment.ARG_JUST_FOLDERS, true);
  125. args.putBoolean(OCFileListFragment.ARG_HIDE_FAB, true);
  126. listOfFiles.setArguments(args);
  127. FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
  128. transaction.add(R.id.fragment_container, listOfFiles, TAG_LIST_OF_FOLDERS);
  129. transaction.commit();
  130. }
  131. /**
  132. * Show a text message on screen view for notifying user if content is
  133. * loading or folder is empty
  134. */
  135. private void setBackgroundText() {
  136. OCFileListFragment listFragment = getListOfFilesFragment();
  137. if (listFragment != null) {
  138. int message = R.string.file_list_loading;
  139. if (!mSyncInProgress) {
  140. // In case folder list is empty
  141. message = R.string.file_list_empty_moving;
  142. }
  143. listFragment.setMessageForEmptyList(getString(message));
  144. } else {
  145. Log.e(TAG, "OCFileListFragment is null");
  146. }
  147. }
  148. protected OCFileListFragment getListOfFilesFragment() {
  149. Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FolderPickerActivity.TAG_LIST_OF_FOLDERS);
  150. if (listOfFiles != null) {
  151. return (OCFileListFragment)listOfFiles;
  152. }
  153. Log_OC.e(TAG, "Access to unexisting list of files fragment!!");
  154. return null;
  155. }
  156. /**
  157. * {@inheritDoc}
  158. *
  159. * Updates action bar and second fragment, if in dual pane mode.
  160. */
  161. @Override
  162. public void onBrowsedDownTo(OCFile directory) {
  163. setFile(directory);
  164. updateNavigationElementsInActionBar();
  165. // Sync Folder
  166. startSyncFolderOperation(directory, false);
  167. }
  168. @Override
  169. public void onSavedCertificate() {
  170. startSyncFolderOperation(getCurrentDir(), false);
  171. }
  172. public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
  173. long currentSyncTime = System.currentTimeMillis();
  174. mSyncInProgress = true;
  175. // perform folder synchronization
  176. RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
  177. currentSyncTime,
  178. false,
  179. getFileOperationsHelper().isSharedSupported(),
  180. ignoreETag,
  181. getStorageManager(),
  182. getAccount(),
  183. getApplicationContext()
  184. );
  185. synchFolderOp.execute(getAccount(), this, null, null);
  186. setIndeterminate(true);
  187. setBackgroundText();
  188. }
  189. @Override
  190. protected void onResume() {
  191. super.onResume();
  192. Log_OC.e(TAG, "onResume() start");
  193. // refresh list of files
  194. refreshListOfFilesFragment();
  195. // Listen for sync messages
  196. IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
  197. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
  198. syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
  199. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  200. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  201. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  202. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  203. Log_OC.d(TAG, "onResume() end");
  204. }
  205. @Override
  206. protected void onPause() {
  207. Log_OC.e(TAG, "onPause() start");
  208. if (mSyncBroadcastReceiver != null) {
  209. unregisterReceiver(mSyncBroadcastReceiver);
  210. //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
  211. mSyncBroadcastReceiver = null;
  212. }
  213. Log_OC.d(TAG, "onPause() end");
  214. super.onPause();
  215. }
  216. @Override
  217. public boolean onCreateOptionsMenu(Menu menu) {
  218. MenuInflater inflater = getMenuInflater();
  219. inflater.inflate(R.menu.main_menu, menu);
  220. menu.findItem(R.id.action_sort).setVisible(false);
  221. return true;
  222. }
  223. @Override
  224. public boolean onOptionsItemSelected(MenuItem item) {
  225. boolean retval = true;
  226. switch (item.getItemId()) {
  227. case R.id.action_create_dir: {
  228. CreateFolderDialogFragment dialog =
  229. CreateFolderDialogFragment.newInstance(getCurrentFolder());
  230. dialog.show(
  231. getSupportFragmentManager(),
  232. CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT
  233. );
  234. break;
  235. }
  236. case android.R.id.home: {
  237. OCFile currentDir = getCurrentFolder();
  238. if(currentDir != null && currentDir.getParentId() != 0) {
  239. onBackPressed();
  240. }
  241. break;
  242. }
  243. default:
  244. retval = super.onOptionsItemSelected(item);
  245. }
  246. return retval;
  247. }
  248. protected OCFile getCurrentFolder() {
  249. OCFile file = getFile();
  250. if (file != null) {
  251. if (file.isFolder()) {
  252. return file;
  253. } else if (getStorageManager() != null) {
  254. String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
  255. return getStorageManager().getFileByPath(parentPath);
  256. }
  257. }
  258. return null;
  259. }
  260. protected void refreshListOfFilesFragment() {
  261. OCFileListFragment fileListFragment = getListOfFilesFragment();
  262. if (fileListFragment != null) {
  263. fileListFragment.listDirectory(false);
  264. }
  265. }
  266. public void browseToRoot() {
  267. OCFileListFragment listOfFiles = getListOfFilesFragment();
  268. if (listOfFiles != null) { // should never be null, indeed
  269. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  270. listOfFiles.listDirectory(root, false);
  271. setFile(listOfFiles.getCurrentFile());
  272. updateNavigationElementsInActionBar();
  273. startSyncFolderOperation(root, false);
  274. }
  275. }
  276. @Override
  277. public void onBackPressed() {
  278. OCFileListFragment listOfFiles = getListOfFilesFragment();
  279. if (listOfFiles != null) { // should never be null, indeed
  280. int levelsUp = listOfFiles.onBrowseUp();
  281. if (levelsUp == 0) {
  282. finish();
  283. return;
  284. }
  285. setFile(listOfFiles.getCurrentFile());
  286. updateNavigationElementsInActionBar();
  287. }
  288. }
  289. protected void updateNavigationElementsInActionBar() {
  290. ActionBar actionBar = getSupportActionBar();
  291. OCFile currentDir = getCurrentFolder();
  292. boolean atRoot = (currentDir == null || currentDir.getParentId() == 0);
  293. actionBar.setDisplayHomeAsUpEnabled(!atRoot);
  294. actionBar.setHomeButtonEnabled(!atRoot);
  295. actionBar.setTitle(
  296. atRoot
  297. ? caption
  298. : currentDir.getFileName()
  299. );
  300. }
  301. /**
  302. * Set per-view controllers
  303. */
  304. private void initControls(){
  305. mCancelBtn = (Button) findViewById(R.id.folder_picker_btn_cancel);
  306. mCancelBtn.setOnClickListener(this);
  307. mChooseBtn = (Button) findViewById(R.id.folder_picker_btn_choose);
  308. mChooseBtn.setOnClickListener(this);
  309. }
  310. @Override
  311. public void onClick(View v) {
  312. if (v.equals(mCancelBtn)) {
  313. finish();
  314. } else if (v.equals(mChooseBtn)) {
  315. Intent i = getIntent();
  316. ArrayList<Parcelable> targetFiles = i.getParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES);
  317. Intent data = new Intent();
  318. data.putExtra(EXTRA_FOLDER, getCurrentFolder());
  319. data.putParcelableArrayListExtra(EXTRA_FILES, targetFiles);
  320. setResult(RESULT_OK, data);
  321. finish();
  322. }
  323. }
  324. @Override
  325. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  326. super.onRemoteOperationFinish(operation, result);
  327. if (operation instanceof CreateFolderOperation) {
  328. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  329. }
  330. }
  331. /**
  332. * Updates the view associated to the activity after the finish of an operation trying
  333. * to create a new folder.
  334. *
  335. * @param operation Creation operation performed.
  336. * @param result Result of the creation.
  337. */
  338. private void onCreateFolderOperationFinish(
  339. CreateFolderOperation operation, RemoteOperationResult result
  340. ) {
  341. if (result.isSuccess()) {
  342. refreshListOfFilesFragment();
  343. } else {
  344. try {
  345. Toast msg = Toast.makeText(FolderPickerActivity.this,
  346. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  347. Toast.LENGTH_LONG);
  348. msg.show();
  349. } catch (NotFoundException e) {
  350. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  351. }
  352. }
  353. }
  354. private class SyncBroadcastReceiver extends BroadcastReceiver {
  355. /**
  356. * {@link BroadcastReceiver} to enable syncing feedback in UI
  357. */
  358. @Override
  359. public void onReceive(Context context, Intent intent) {
  360. try {
  361. String event = intent.getAction();
  362. Log_OC.d(TAG, "Received broadcast " + event);
  363. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  364. String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  365. RemoteOperationResult synchResult = (RemoteOperationResult)intent.
  366. getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
  367. boolean sameAccount = (getAccount() != null &&
  368. accountName.equals(getAccount().name) && getStorageManager() != null);
  369. if (sameAccount) {
  370. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  371. mSyncInProgress = true;
  372. } else {
  373. OCFile currentFile = (getFile() == null) ? null :
  374. getStorageManager().getFileByPath(getFile().getRemotePath());
  375. OCFile currentDir = (getCurrentFolder() == null) ? null :
  376. getStorageManager().getFileByPath(getCurrentFolder().getRemotePath());
  377. if (currentDir == null) {
  378. // current folder was removed from the server
  379. Toast.makeText( FolderPickerActivity.this,
  380. String.format(
  381. getString(R.string.sync_current_folder_was_removed),
  382. getCurrentFolder().getFileName()),
  383. Toast.LENGTH_LONG)
  384. .show();
  385. browseToRoot();
  386. } else {
  387. if (currentFile == null && !getFile().isFolder()) {
  388. // currently selected file was removed in the server, and now we know it
  389. currentFile = currentDir;
  390. }
  391. if (currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  392. OCFileListFragment fileListFragment = getListOfFilesFragment();
  393. if (fileListFragment != null) {
  394. fileListFragment.listDirectory(currentDir, false);
  395. }
  396. }
  397. setFile(currentFile);
  398. }
  399. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  400. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  401. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  402. equals(event) &&
  403. /// TODO refactor and make common
  404. synchResult != null && !synchResult.isSuccess()) {
  405. if(ResultCode.UNAUTHORIZED.equals(synchResult.getCode()) ||
  406. (synchResult.isException() && synchResult.getException()
  407. instanceof AuthenticatorException)) {
  408. requestCredentialsUpdate(context);
  409. } else if(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(synchResult.getCode())) {
  410. showUntrustedCertDialog(synchResult);
  411. }
  412. }
  413. }
  414. removeStickyBroadcast(intent);
  415. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  416. setIndeterminate(mSyncInProgress);
  417. setBackgroundText();
  418. }
  419. } catch (RuntimeException e) {
  420. // avoid app crashes after changing the serial id of RemoteOperationResult
  421. // in owncloud library with broadcast notifications pending to process
  422. removeStickyBroadcast(intent);
  423. }
  424. }
  425. }
  426. /**
  427. * Shows the information of the {@link OCFile} received as a
  428. * parameter in the second fragment.
  429. *
  430. * @param file {@link OCFile} whose details will be shown
  431. */
  432. @Override
  433. public void showDetails(OCFile file) {
  434. }
  435. /**
  436. * {@inheritDoc}
  437. */
  438. @Override
  439. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  440. }
  441. @Override
  442. public void onRefresh() {
  443. refreshList(true);
  444. }
  445. @Override
  446. public void onRefresh(boolean enforced) {
  447. refreshList(enforced);
  448. }
  449. private void refreshList(boolean ignoreETag) {
  450. OCFileListFragment listOfFiles = getListOfFilesFragment();
  451. if (listOfFiles != null) {
  452. OCFile folder = listOfFiles.getCurrentFile();
  453. if (folder != null) {
  454. startSyncFolderOperation(folder, ignoreETag);
  455. }
  456. }
  457. }
  458. }