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