FolderPickerActivity.java 20 KB

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