#819 part3: When uploading from filesystem inside the owncloud app, show question
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / UploadFilesActivity.java
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
21 package com.owncloud.android.ui.activity;
22
23 import android.accounts.Account;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.os.AsyncTask;
27 import android.os.Bundle;
28 import android.os.Environment;
29 import android.preference.PreferenceManager;
30 import android.support.v4.app.DialogFragment;
31 import android.support.v7.app.ActionBar;
32 import android.view.MenuItem;
33 import android.view.View;
34 import android.view.View.OnClickListener;
35 import android.view.ViewGroup;
36 import android.widget.ArrayAdapter;
37 import android.widget.Button;
38 import android.widget.RadioButton;
39 import android.widget.TextView;
40
41 import com.owncloud.android.R;
42 import com.owncloud.android.files.services.FileUploader;
43 import com.owncloud.android.lib.common.utils.Log_OC;
44 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
45 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
46 import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
47 import com.owncloud.android.ui.fragment.LocalFileListFragment;
48 import com.owncloud.android.utils.FileStorageUtils;
49
50 import java.io.File;
51
52
53 /**
54 * Displays local files and let the user choose what of them wants to upload
55 * to the current ownCloud account
56 */
57
58 public class UploadFilesActivity extends FileActivity implements
59 LocalFileListFragment.ContainerActivity, ActionBar.OnNavigationListener,
60 OnClickListener, ConfirmationDialogFragmentListener {
61
62 private ArrayAdapter<String> mDirectories;
63 private File mCurrentDir = null;
64 private LocalFileListFragment mFileListFragment;
65 private Button mCancelBtn;
66 private Button mUploadBtn;
67 private Account mAccountOnCreation;
68 private DialogFragment mCurrentDialog;
69
70 public static final String EXTRA_CHOSEN_FILES =
71 UploadFilesActivity.class.getCanonicalName() + ".EXTRA_CHOSEN_FILES";
72
73 public static final int RESULT_OK_AND_MOVE = RESULT_FIRST_USER;
74
75 private static final String KEY_DIRECTORY_PATH =
76 UploadFilesActivity.class.getCanonicalName() + ".KEY_DIRECTORY_PATH";
77 private static final String TAG = "UploadFilesActivity";
78 private static final String WAIT_DIALOG_TAG = "WAIT";
79 private static final String QUERY_TO_MOVE_DIALOG_TAG = "QUERY_TO_MOVE";
80 private RadioButton mRadioBtnCopyFiles;
81 private RadioButton mRadioBtnMoveFiles;
82
83
84 @Override
85 public void onCreate(Bundle savedInstanceState) {
86 Log_OC.d(TAG, "onCreate() start");
87 super.onCreate(savedInstanceState);
88
89 if(savedInstanceState != null) {
90 mCurrentDir = new File(savedInstanceState.getString(
91 UploadFilesActivity.KEY_DIRECTORY_PATH));
92 } else {
93 mCurrentDir = Environment.getExternalStorageDirectory();
94 }
95
96 mAccountOnCreation = getAccount();
97
98 /// USER INTERFACE
99
100 // Drop-down navigation
101 mDirectories = new CustomArrayAdapter<String>(this,
102 R.layout.support_simple_spinner_dropdown_item);
103 File currDir = mCurrentDir;
104 while(currDir != null && currDir.getParentFile() != null) {
105 mDirectories.add(currDir.getName());
106 currDir = currDir.getParentFile();
107 }
108 mDirectories.add(File.separator);
109
110 // Inflate and set the layout view
111 setContentView(R.layout.upload_files_layout);
112 mFileListFragment = (LocalFileListFragment)
113 getSupportFragmentManager().findFragmentById(R.id.local_files_list);
114
115
116 // Set input controllers
117 mCancelBtn = (Button) findViewById(R.id.upload_files_btn_cancel);
118 mCancelBtn.setOnClickListener(this);
119 mUploadBtn = (Button) findViewById(R.id.upload_files_btn_upload);
120 mUploadBtn.setOnClickListener(this);
121
122 SharedPreferences appPreferences = PreferenceManager
123 .getDefaultSharedPreferences(getApplicationContext());
124
125 Integer localBehaviour = appPreferences.getInt("prefs_uploader_behaviour", FileUploader.LOCAL_BEHAVIOUR_COPY);
126
127 mRadioBtnMoveFiles = (RadioButton) findViewById(R.id.upload_radio_move);
128 if (localBehaviour == FileUploader.LOCAL_BEHAVIOUR_MOVE){
129 mRadioBtnMoveFiles.setChecked(true);
130 }
131
132 mRadioBtnCopyFiles = (RadioButton) findViewById(R.id.upload_radio_copy);
133 if (localBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY){
134 mRadioBtnCopyFiles.setChecked(true);
135 }
136
137
138 // Action bar setup
139 ActionBar actionBar = getSupportActionBar();
140 actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the
141 // official documentation
142 actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getName() != null);
143 actionBar.setDisplayShowTitleEnabled(false);
144 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
145 actionBar.setListNavigationCallbacks(mDirectories, this);
146
147 // wait dialog
148 if (mCurrentDialog != null) {
149 mCurrentDialog.dismiss();
150 mCurrentDialog = null;
151 }
152
153 Log_OC.d(TAG, "onCreate() end");
154 }
155
156
157 @Override
158 public boolean onOptionsItemSelected(MenuItem item) {
159 boolean retval = true;
160 switch (item.getItemId()) {
161 case android.R.id.home: {
162 if(mCurrentDir != null && mCurrentDir.getParentFile() != null){
163 onBackPressed();
164 }
165 break;
166 }
167 default:
168 retval = super.onOptionsItemSelected(item);
169 }
170 return retval;
171 }
172
173
174 @Override
175 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
176 int i = itemPosition;
177 while (i-- != 0) {
178 onBackPressed();
179 }
180 // the next operation triggers a new call to this method, but it's necessary to
181 // ensure that the name exposed in the action bar is the current directory when the
182 // user selected it in the navigation list
183 if (itemPosition != 0)
184 getSupportActionBar().setSelectedNavigationItem(0);
185 return true;
186 }
187
188
189 @Override
190 public void onBackPressed() {
191 if (mDirectories.getCount() <= 1) {
192 finish();
193 return;
194 }
195 popDirname();
196 mFileListFragment.onNavigateUp();
197 mCurrentDir = mFileListFragment.getCurrentDirectory();
198
199 if(mCurrentDir.getParentFile() == null){
200 ActionBar actionBar = getSupportActionBar();
201 actionBar.setDisplayHomeAsUpEnabled(false);
202 }
203 }
204
205
206 @Override
207 protected void onSaveInstanceState(Bundle outState) {
208 // responsibility of restore is preferred in onCreate() before than in
209 // onRestoreInstanceState when there are Fragments involved
210 Log_OC.d(TAG, "onSaveInstanceState() start");
211 super.onSaveInstanceState(outState);
212 outState.putString(UploadFilesActivity.KEY_DIRECTORY_PATH, mCurrentDir.getAbsolutePath());
213 Log_OC.d(TAG, "onSaveInstanceState() end");
214 }
215
216
217 /**
218 * Pushes a directory to the drop down list
219 * @param directory to push
220 * @throws IllegalArgumentException If the {@link File#isDirectory()} returns false.
221 */
222 public void pushDirname(File directory) {
223 if(!directory.isDirectory()){
224 throw new IllegalArgumentException("Only directories may be pushed!");
225 }
226 mDirectories.insert(directory.getName(), 0);
227 mCurrentDir = directory;
228 }
229
230 /**
231 * Pops a directory name from the drop down list
232 * @return True, unless the stack is empty
233 */
234 public boolean popDirname() {
235 mDirectories.remove(mDirectories.getItem(0));
236 return !mDirectories.isEmpty();
237 }
238
239
240 // Custom array adapter to override text colors
241 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
242
243 public CustomArrayAdapter(UploadFilesActivity ctx, int view) {
244 super(ctx, view);
245 }
246
247 public View getView(int position, View convertView, ViewGroup parent) {
248 View v = super.getView(position, convertView, parent);
249
250 ((TextView) v).setTextColor(getResources().getColorStateList(
251 android.R.color.white));
252 return v;
253 }
254
255 public View getDropDownView(int position, View convertView,
256 ViewGroup parent) {
257 View v = super.getDropDownView(position, convertView, parent);
258
259 ((TextView) v).setTextColor(getResources().getColorStateList(
260 android.R.color.white));
261
262 return v;
263 }
264
265 }
266
267 /**
268 * {@inheritDoc}
269 */
270 @Override
271 public void onDirectoryClick(File directory) {
272 pushDirname(directory);
273 ActionBar actionBar = getSupportActionBar();
274 actionBar.setDisplayHomeAsUpEnabled(true);
275 }
276
277
278 /**
279 * {@inheritDoc}
280 */
281 @Override
282 public void onFileClick(File file) {
283 // nothing to do
284 }
285
286 /**
287 * {@inheritDoc}
288 */
289 @Override
290 public File getInitialDirectory() {
291 return mCurrentDir;
292 }
293
294
295 /**
296 * Performs corresponding action when user presses 'Cancel' or 'Upload' button
297 *
298 * TODO Make here the real request to the Upload service ; will require to receive the account and
299 * target folder where the upload must be done in the received intent.
300 */
301 @Override
302 public void onClick(View v) {
303 if (v.getId() == R.id.upload_files_btn_cancel) {
304 setResult(RESULT_CANCELED);
305 finish();
306
307 } else if (v.getId() == R.id.upload_files_btn_upload) {
308 new CheckAvailableSpaceTask().execute();
309 }
310 }
311
312
313 /**
314 * Asynchronous task checking if there is space enough to copy all the files chosen
315 * to upload into the ownCloud local folder.
316 *
317 * Maybe an AsyncTask is not strictly necessary, but who really knows.
318 */
319 private class CheckAvailableSpaceTask extends AsyncTask<Void, Void, Boolean> {
320
321 /**
322 * Updates the UI before trying the movement
323 */
324 @Override
325 protected void onPreExecute () {
326 /// progress dialog and disable 'Move' button
327 mCurrentDialog = IndeterminateProgressDialog.newInstance(R.string.wait_a_moment, false);
328 mCurrentDialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
329 }
330
331
332 /**
333 * Checks the available space
334 *
335 * @return 'True' if there is space enough.
336 */
337 @Override
338 protected Boolean doInBackground(Void... params) {
339 String[] checkedFilePaths = mFileListFragment.getCheckedFilePaths();
340 long total = 0;
341 for (int i=0; checkedFilePaths != null && i < checkedFilePaths.length ; i++) {
342 String localPath = checkedFilePaths[i];
343 File localFile = new File(localPath);
344 total += localFile.length();
345 }
346 return (new Boolean(FileStorageUtils.getUsableSpace(mAccountOnCreation.name) >= total));
347 }
348
349 /**
350 * Updates the activity UI after the check of space is done.
351 *
352 * If there is not space enough. shows a new dialog to query the user if wants to move the files instead
353 * of copy them.
354 *
355 * @param result 'True' when there is space enough to copy all the selected files.
356 */
357 @Override
358 protected void onPostExecute(Boolean result) {
359 mCurrentDialog.dismiss();
360 mCurrentDialog = null;
361
362 if (result) {
363 // return the list of selected files (success)
364 Intent data = new Intent();
365 data.putExtra(EXTRA_CHOSEN_FILES, mFileListFragment.getCheckedFilePaths());
366
367 SharedPreferences.Editor appPreferencesEditor = PreferenceManager
368 .getDefaultSharedPreferences(getApplicationContext()).edit();
369
370
371 if (mRadioBtnMoveFiles.isChecked()){
372 setResult(RESULT_OK_AND_MOVE, data);
373 appPreferencesEditor.putInt("prefs_uploader_behaviour",
374 FileUploader.LOCAL_BEHAVIOUR_MOVE);
375 } else {
376 setResult(RESULT_OK, data);
377 appPreferencesEditor.putInt("prefs_uploader_behaviour",
378 FileUploader.LOCAL_BEHAVIOUR_COPY);
379 }
380 appPreferencesEditor.apply();
381 finish();
382 } else {
383 // show a dialog to query the user if wants to move the selected files
384 // to the ownCloud folder instead of copying
385 String[] args = {getString(R.string.app_name)};
386 ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance(
387 R.string.upload_query_move_foreign_files, args, R.string.common_yes, -1, R.string.common_no
388 );
389 dialog.setOnConfirmationListener(UploadFilesActivity.this);
390 dialog.show(getSupportFragmentManager(), QUERY_TO_MOVE_DIALOG_TAG);
391 }
392 }
393 }
394
395 @Override
396 public void onConfirmation(String callerTag) {
397 Log_OC.d(TAG, "Positive button in dialog was clicked; dialog tag is " + callerTag);
398 if (callerTag.equals(QUERY_TO_MOVE_DIALOG_TAG)) {
399 // return the list of selected files to the caller activity (success),
400 // signaling that they should be moved to the ownCloud folder, instead of copied
401 Intent data = new Intent();
402 data.putExtra(EXTRA_CHOSEN_FILES, mFileListFragment.getCheckedFilePaths());
403 setResult(RESULT_OK_AND_MOVE, data);
404 finish();
405 }
406 }
407
408
409 @Override
410 public void onNeutral(String callerTag) {
411 Log_OC.d(TAG, "Phantom neutral button in dialog was clicked; dialog tag is " + callerTag);
412 }
413
414
415 @Override
416 public void onCancel(String callerTag) {
417 /// nothing to do; don't finish, let the user change the selection
418 Log_OC.d(TAG, "Negative button in dialog was clicked; dialog tag is " + callerTag);
419 }
420
421
422 @Override
423 protected void onAccountSet(boolean stateWasRecovered) {
424 super.onAccountSet(stateWasRecovered);
425 if (getAccount() != null) {
426 if (!mAccountOnCreation.equals(getAccount())) {
427 setResult(RESULT_CANCELED);
428 finish();
429 }
430
431 } else {
432 setResult(RESULT_CANCELED);
433 finish();
434 }
435 }
436
437
438 }