UploadFilesActivity.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2015 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package com.owncloud.android.ui.activity;
  21. import android.accounts.Account;
  22. import android.app.Activity;
  23. import android.app.AlertDialog;
  24. import android.content.DialogInterface;
  25. import android.content.Intent;
  26. import android.os.AsyncTask;
  27. import android.os.Bundle;
  28. import android.os.Environment;
  29. import android.support.v4.app.DialogFragment;
  30. import android.support.v4.app.Fragment;
  31. import android.support.v4.content.ContextCompat;
  32. import android.support.v7.app.ActionBar;
  33. import android.view.Menu;
  34. import android.view.MenuItem;
  35. import android.view.View;
  36. import android.view.View.OnClickListener;
  37. import android.view.ViewGroup;
  38. import android.widget.ArrayAdapter;
  39. import android.widget.Button;
  40. import android.widget.Spinner;
  41. import android.widget.TextView;
  42. import com.owncloud.android.R;
  43. import com.owncloud.android.db.PreferenceManager;
  44. import com.owncloud.android.lib.common.utils.Log_OC;
  45. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  46. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
  47. import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
  48. import com.owncloud.android.ui.fragment.ExtendedListFragment;
  49. import com.owncloud.android.ui.fragment.LocalFileListFragment;
  50. import com.owncloud.android.utils.FileStorageUtils;
  51. import java.io.File;
  52. /**
  53. * Displays local files and let the user choose what of them wants to upload
  54. * to the current ownCloud account.
  55. */
  56. public class UploadFilesActivity extends FileActivity implements
  57. LocalFileListFragment.ContainerActivity, ActionBar.OnNavigationListener,
  58. OnClickListener, ConfirmationDialogFragmentListener {
  59. private ArrayAdapter<String> mDirectories;
  60. private File mCurrentDir = null;
  61. private boolean mSelectAll = false;
  62. private LocalFileListFragment mFileListFragment;
  63. private Button mCancelBtn;
  64. private Button mUploadBtn;
  65. private Spinner mBehaviourSpinner;
  66. private Account mAccountOnCreation;
  67. private DialogFragment mCurrentDialog;
  68. private Menu mOptionsMenu;
  69. public static final String EXTRA_CHOSEN_FILES =
  70. UploadFilesActivity.class.getCanonicalName() + ".EXTRA_CHOSEN_FILES";
  71. public static final int RESULT_OK_AND_MOVE = RESULT_FIRST_USER;
  72. public static final int RESULT_OK_AND_DO_NOTHING = 2;
  73. public static final int RESULT_OK_AND_DELETE = 3;
  74. private static final String KEY_DIRECTORY_PATH =
  75. UploadFilesActivity.class.getCanonicalName() + ".KEY_DIRECTORY_PATH";
  76. private static final String KEY_ALL_SELECTED =
  77. UploadFilesActivity.class.getCanonicalName() + ".KEY_ALL_SELECTED";
  78. private static final String TAG = "UploadFilesActivity";
  79. private static final String WAIT_DIALOG_TAG = "WAIT";
  80. private static final String QUERY_TO_MOVE_DIALOG_TAG = "QUERY_TO_MOVE";
  81. @Override
  82. public void onCreate(Bundle savedInstanceState) {
  83. Log_OC.d(TAG, "onCreate() start");
  84. super.onCreate(savedInstanceState);
  85. if(savedInstanceState != null) {
  86. mCurrentDir = new File(savedInstanceState.getString(UploadFilesActivity.KEY_DIRECTORY_PATH, Environment
  87. .getExternalStorageDirectory().getAbsolutePath()));
  88. mSelectAll = savedInstanceState.getBoolean(UploadFilesActivity.KEY_ALL_SELECTED, false);
  89. } else {
  90. mCurrentDir = Environment.getExternalStorageDirectory();
  91. }
  92. mAccountOnCreation = getAccount();
  93. /// USER INTERFACE
  94. // Drop-down navigation
  95. mDirectories = new CustomArrayAdapter<String>(this,
  96. R.layout.support_simple_spinner_dropdown_item);
  97. File currDir = mCurrentDir;
  98. while(currDir != null && currDir.getParentFile() != null) {
  99. mDirectories.add(currDir.getName());
  100. currDir = currDir.getParentFile();
  101. }
  102. mDirectories.add(File.separator);
  103. // Inflate and set the layout view
  104. setContentView(R.layout.upload_files_layout);
  105. mFileListFragment = (LocalFileListFragment)
  106. getSupportFragmentManager().findFragmentById(R.id.local_files_list);
  107. // Set input controllers
  108. mCancelBtn = (Button) findViewById(R.id.upload_files_btn_cancel);
  109. mCancelBtn.setOnClickListener(this);
  110. mUploadBtn = (Button) findViewById(R.id.upload_files_btn_upload);
  111. mUploadBtn.setOnClickListener(this);
  112. int localBehaviour = PreferenceManager.getUploaderBehaviour(this);
  113. // file upload spinner
  114. mBehaviourSpinner = (Spinner) findViewById(R.id.upload_files_spinner_behaviour);
  115. ArrayAdapter<CharSequence> behaviourAdapter = ArrayAdapter.createFromResource(this,
  116. R.array.upload_files_behaviour, android.R.layout.simple_spinner_item);
  117. behaviourAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  118. mBehaviourSpinner.setAdapter(behaviourAdapter);
  119. mBehaviourSpinner.setSelection(localBehaviour);
  120. // setup the toolbar
  121. setupToolbar();
  122. // Action bar setup
  123. ActionBar actionBar = getSupportActionBar();
  124. actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the
  125. // official documentation
  126. actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getName() != null);
  127. actionBar.setDisplayShowTitleEnabled(false);
  128. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
  129. actionBar.setListNavigationCallbacks(mDirectories, this);
  130. // wait dialog
  131. if (mCurrentDialog != null) {
  132. mCurrentDialog.dismiss();
  133. mCurrentDialog = null;
  134. }
  135. Log_OC.d(TAG, "onCreate() end");
  136. }
  137. /**
  138. * Helper to launch the UploadFilesActivity for which you would like a result when it finished.
  139. * Your onActivityResult() method will be called with the given requestCode.
  140. *
  141. * @param activity the activity which should call the upload activity for a result
  142. * @param account the account for which the upload activity is called
  143. * @param requestCode If >= 0, this code will be returned in onActivityResult()
  144. */
  145. public static void startUploadActivityForResult(Activity activity, Account account, int requestCode) {
  146. Intent action = new Intent(activity, UploadFilesActivity.class);
  147. action.putExtra(EXTRA_ACCOUNT, (account));
  148. activity.startActivityForResult(action, requestCode);
  149. }
  150. @Override
  151. public boolean onCreateOptionsMenu(Menu menu) {
  152. mOptionsMenu = menu;
  153. getMenuInflater().inflate(R.menu.upload_files_picker, menu);
  154. MenuItem selectAll = menu.findItem(R.id.action_select_all);
  155. setSelectAllMenuItem(selectAll, mSelectAll);
  156. return super.onCreateOptionsMenu(menu);
  157. }
  158. @Override
  159. public boolean onOptionsItemSelected(MenuItem item) {
  160. boolean retval = true;
  161. switch (item.getItemId()) {
  162. case android.R.id.home: {
  163. if(mCurrentDir != null && mCurrentDir.getParentFile() != null){
  164. onBackPressed();
  165. }
  166. break;
  167. }
  168. case R.id.action_select_all: {
  169. item.setChecked(!item.isChecked());
  170. mSelectAll = item.isChecked();
  171. setSelectAllMenuItem(item, mSelectAll);
  172. mFileListFragment.selectAllFiles(item.isChecked());
  173. break;
  174. }
  175. case R.id.action_sort: {
  176. // Read sorting order, default to sort by name ascending
  177. Integer sortOrder = PreferenceManager.getSortOrder(this);
  178. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  179. builder.setTitle(R.string.actionbar_sort_title)
  180. .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder ,
  181. new DialogInterface.OnClickListener() {
  182. public void onClick(DialogInterface dialog, int which) {
  183. switch (which){
  184. case 0:
  185. mFileListFragment.sortByName(true);
  186. break;
  187. case 1:
  188. mFileListFragment.sortByDate(false);
  189. break;
  190. }
  191. dialog.dismiss();
  192. }
  193. });
  194. builder.create().show();
  195. break;
  196. }
  197. case R.id.action_switch_view: {
  198. if (isGridView()) {
  199. item.setTitle(getString(R.string.action_switch_grid_view));
  200. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  201. R.drawable.ic_view_module));
  202. mFileListFragment.switchToListView();
  203. } else {
  204. item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
  205. item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
  206. R.drawable.ic_view_list));
  207. mFileListFragment.switchToGridView();
  208. }
  209. return true;
  210. }
  211. default:
  212. retval = super.onOptionsItemSelected(item);
  213. }
  214. return retval;
  215. }
  216. @Override
  217. public boolean onNavigationItemSelected(int itemPosition, long itemId) {
  218. int i = itemPosition;
  219. while (i-- != 0) {
  220. onBackPressed();
  221. }
  222. // the next operation triggers a new call to this method, but it's necessary to
  223. // ensure that the name exposed in the action bar is the current directory when the
  224. // user selected it in the navigation list
  225. if (itemPosition != 0)
  226. getSupportActionBar().setSelectedNavigationItem(0);
  227. return true;
  228. }
  229. @Override
  230. public void onBackPressed() {
  231. if (mDirectories.getCount() <= 1) {
  232. finish();
  233. return;
  234. }
  235. popDirname();
  236. mFileListFragment.onNavigateUp();
  237. mCurrentDir = mFileListFragment.getCurrentDirectory();
  238. if(mCurrentDir.getParentFile() == null){
  239. ActionBar actionBar = getSupportActionBar();
  240. actionBar.setDisplayHomeAsUpEnabled(false);
  241. }
  242. // invalidate checked state when navigating directories
  243. setSelectAllMenuItem(mOptionsMenu.findItem(R.id.action_select_all), false);
  244. }
  245. @Override
  246. protected void onSaveInstanceState(Bundle outState) {
  247. // responsibility of restore is preferred in onCreate() before than in
  248. // onRestoreInstanceState when there are Fragments involved
  249. Log_OC.d(TAG, "onSaveInstanceState() start");
  250. super.onSaveInstanceState(outState);
  251. outState.putString(UploadFilesActivity.KEY_DIRECTORY_PATH, mCurrentDir.getAbsolutePath());
  252. outState.putBoolean(UploadFilesActivity.KEY_ALL_SELECTED,
  253. mOptionsMenu.findItem(R.id.action_select_all).isChecked());
  254. Log_OC.d(TAG, "onSaveInstanceState() end");
  255. }
  256. /**
  257. * Pushes a directory to the drop down list
  258. * @param directory to push
  259. * @throws IllegalArgumentException If the {@link File#isDirectory()} returns false.
  260. */
  261. public void pushDirname(File directory) {
  262. if(!directory.isDirectory()){
  263. throw new IllegalArgumentException("Only directories may be pushed!");
  264. }
  265. mDirectories.insert(directory.getName(), 0);
  266. mCurrentDir = directory;
  267. }
  268. /**
  269. * Pops a directory name from the drop down list
  270. * @return True, unless the stack is empty
  271. */
  272. public boolean popDirname() {
  273. mDirectories.remove(mDirectories.getItem(0));
  274. return !mDirectories.isEmpty();
  275. }
  276. private void setSelectAllMenuItem(MenuItem selectAll, boolean checked) {
  277. selectAll.setChecked(checked);
  278. if(checked) {
  279. selectAll.setIcon(R.drawable.ic_select_none);
  280. } else {
  281. selectAll.setIcon(R.drawable.ic_select_all);
  282. }
  283. }
  284. // Custom array adapter to override text colors
  285. private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
  286. public CustomArrayAdapter(UploadFilesActivity ctx, int view) {
  287. super(ctx, view);
  288. }
  289. public View getView(int position, View convertView, ViewGroup parent) {
  290. View v = super.getView(position, convertView, parent);
  291. ((TextView) v).setTextColor(getResources().getColorStateList(
  292. android.R.color.white));
  293. return v;
  294. }
  295. public View getDropDownView(int position, View convertView,
  296. ViewGroup parent) {
  297. View v = super.getDropDownView(position, convertView, parent);
  298. ((TextView) v).setTextColor(getResources().getColorStateList(
  299. android.R.color.white));
  300. return v;
  301. }
  302. }
  303. /**
  304. * {@inheritDoc}
  305. */
  306. @Override
  307. public void onDirectoryClick(File directory) {
  308. // invalidate checked state when navigating directories
  309. MenuItem selectAll = mOptionsMenu.findItem(R.id.action_select_all);
  310. setSelectAllMenuItem(selectAll, false);
  311. pushDirname(directory);
  312. ActionBar actionBar = getSupportActionBar();
  313. actionBar.setDisplayHomeAsUpEnabled(true);
  314. }
  315. /**
  316. * {@inheritDoc}
  317. */
  318. @Override
  319. public void onFileClick(File file) {
  320. // nothing to do
  321. }
  322. /**
  323. * {@inheritDoc}
  324. */
  325. @Override
  326. public File getInitialDirectory() {
  327. return mCurrentDir;
  328. }
  329. /**
  330. * Performs corresponding action when user presses 'Cancel' or 'Upload' button
  331. *
  332. * TODO Make here the real request to the Upload service ; will require to receive the account and
  333. * target folder where the upload must be done in the received intent.
  334. */
  335. @Override
  336. public void onClick(View v) {
  337. if (v.getId() == R.id.upload_files_btn_cancel) {
  338. setResult(RESULT_CANCELED);
  339. finish();
  340. } else if (v.getId() == R.id.upload_files_btn_upload) {
  341. new CheckAvailableSpaceTask().execute(mBehaviourSpinner.getSelectedItemPosition()==0);
  342. }
  343. }
  344. /**
  345. * Asynchronous task checking if there is space enough to copy all the files chosen
  346. * to upload into the ownCloud local folder.
  347. *
  348. * Maybe an AsyncTask is not strictly necessary, but who really knows.
  349. */
  350. private class CheckAvailableSpaceTask extends AsyncTask<Boolean, Void, Boolean> {
  351. /**
  352. * Updates the UI before trying the movement
  353. */
  354. @Override
  355. protected void onPreExecute () {
  356. /// progress dialog and disable 'Move' button
  357. mCurrentDialog = IndeterminateProgressDialog.newInstance(R.string.wait_a_moment, false);
  358. mCurrentDialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
  359. }
  360. /**
  361. * Checks the available space.
  362. *
  363. * @param params boolean flag if storage calculation should be done.
  364. * @return 'True' if there is space enough or doesn't have to be calculated
  365. */
  366. @Override
  367. protected Boolean doInBackground(Boolean... params) {
  368. if(params[0]) {
  369. String[] checkedFilePaths = mFileListFragment.getCheckedFilePaths();
  370. long total = 0;
  371. for (int i = 0; checkedFilePaths != null && i < checkedFilePaths.length; i++) {
  372. String localPath = checkedFilePaths[i];
  373. File localFile = new File(localPath);
  374. total += localFile.length();
  375. }
  376. return FileStorageUtils.getUsableSpace(mAccountOnCreation.name) >= total;
  377. }
  378. return true;
  379. }
  380. /**
  381. * Updates the activity UI after the check of space is done.
  382. *
  383. * If there is not space enough. shows a new dialog to query the user if wants to move the
  384. * files instead of copy them.
  385. *
  386. * @param result 'True' when there is space enough to copy all the selected files.
  387. */
  388. @Override
  389. protected void onPostExecute(Boolean result) {
  390. if(mCurrentDialog != null) {
  391. mCurrentDialog.dismiss();
  392. mCurrentDialog = null;
  393. }
  394. if (result) {
  395. // return the list of selected files (success)
  396. Intent data = new Intent();
  397. data.putExtra(EXTRA_CHOSEN_FILES, mFileListFragment.getCheckedFilePaths());
  398. // set result code
  399. switch (mBehaviourSpinner.getSelectedItemPosition()) {
  400. case 0: // move to nextcloud folder
  401. setResult(RESULT_OK_AND_MOVE, data);
  402. break;
  403. case 1: // only upload
  404. setResult(RESULT_OK_AND_DO_NOTHING, data);
  405. break;
  406. case 2: // upload and delete from source
  407. setResult(RESULT_OK_AND_DELETE, data);
  408. break;
  409. }
  410. // store behaviour
  411. PreferenceManager.setUploaderBehaviour(getApplicationContext(),
  412. mBehaviourSpinner.getSelectedItemPosition());
  413. finish();
  414. } else {
  415. // show a dialog to query the user if wants to move the selected files
  416. // to the ownCloud folder instead of copying
  417. String[] args = {getString(R.string.app_name)};
  418. ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
  419. R.string.upload_query_move_foreign_files, args, 0, R.string.common_yes, -1,
  420. R.string.common_no
  421. );
  422. dialog.setOnConfirmationListener(UploadFilesActivity.this);
  423. dialog.show(getSupportFragmentManager(), QUERY_TO_MOVE_DIALOG_TAG);
  424. }
  425. }
  426. }
  427. @Override
  428. public void onConfirmation(String callerTag) {
  429. Log_OC.d(TAG, "Positive button in dialog was clicked; dialog tag is " + callerTag);
  430. if (callerTag.equals(QUERY_TO_MOVE_DIALOG_TAG)) {
  431. // return the list of selected files to the caller activity (success),
  432. // signaling that they should be moved to the ownCloud folder, instead of copied
  433. Intent data = new Intent();
  434. data.putExtra(EXTRA_CHOSEN_FILES, mFileListFragment.getCheckedFilePaths());
  435. setResult(RESULT_OK_AND_MOVE, data);
  436. finish();
  437. }
  438. }
  439. @Override
  440. public void onNeutral(String callerTag) {
  441. Log_OC.d(TAG, "Phantom neutral button in dialog was clicked; dialog tag is " + callerTag);
  442. }
  443. @Override
  444. public void onCancel(String callerTag) {
  445. /// nothing to do; don't finish, let the user change the selection
  446. Log_OC.d(TAG, "Negative button in dialog was clicked; dialog tag is " + callerTag);
  447. }
  448. @Override
  449. protected void onAccountSet(boolean stateWasRecovered) {
  450. super.onAccountSet(stateWasRecovered);
  451. if (getAccount() != null) {
  452. if (!mAccountOnCreation.equals(getAccount())) {
  453. setResult(RESULT_CANCELED);
  454. finish();
  455. }
  456. } else {
  457. setResult(RESULT_CANCELED);
  458. finish();
  459. }
  460. }
  461. private boolean isGridView() {
  462. return getListOfFilesFragment().isGridEnabled();
  463. }
  464. private ExtendedListFragment getListOfFilesFragment() {
  465. Fragment listOfFiles = mFileListFragment;
  466. if (listOfFiles != null) {
  467. return (ExtendedListFragment) listOfFiles;
  468. }
  469. Log_OC.e(TAG, "Access to unexisting list of files fragment!!");
  470. return null;
  471. }
  472. }