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