47dae5fa69b25ee448c5ebf06a893caf12f0fe6a
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package eu.alefzero.owncloud.ui.activity;
20
21 import java.io.File;
22 import java.net.URLDecoder;
23 import java.net.URLEncoder;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26
27 import android.accounts.Account;
28 import android.accounts.AccountManager;
29 import android.app.AlertDialog;
30 import android.app.AlertDialog.Builder;
31 import android.app.Dialog;
32 import android.content.BroadcastReceiver;
33 import android.content.ContentResolver;
34 import android.content.Context;
35 import android.content.DialogInterface;
36 import android.content.DialogInterface.OnClickListener;
37 import android.content.Intent;
38 import android.content.IntentFilter;
39 import android.database.Cursor;
40 import android.net.Uri;
41 import android.os.Bundle;
42 import android.provider.MediaStore;
43 import android.util.Log;
44 import android.view.View;
45 import android.view.ViewGroup;
46 import android.widget.ArrayAdapter;
47 import android.widget.EditText;
48 import android.widget.TextView;
49
50 import com.actionbarsherlock.app.ActionBar;
51 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
52 import com.actionbarsherlock.app.SherlockFragmentActivity;
53 import com.actionbarsherlock.view.Menu;
54 import com.actionbarsherlock.view.MenuInflater;
55 import com.actionbarsherlock.view.MenuItem;
56 import com.actionbarsherlock.view.Window;
57
58 import eu.alefzero.owncloud.AccountUtils;
59 import eu.alefzero.owncloud.R;
60 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
61 import eu.alefzero.owncloud.datamodel.DataStorageManager;
62 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
63 import eu.alefzero.owncloud.datamodel.OCFile;
64 import eu.alefzero.owncloud.files.services.FileUploader;
65 import eu.alefzero.owncloud.syncadapter.FileSyncService;
66 import eu.alefzero.owncloud.ui.fragment.FileDetailFragment;
67 import eu.alefzero.owncloud.ui.fragment.FileListFragment;
68 import eu.alefzero.webdav.WebdavClient;
69
70 /**
71 * Displays, what files the user has available in his ownCloud.
72 *
73 * @author Bartek Przybylski
74 *
75 */
76
77 public class FileDisplayActivity extends SherlockFragmentActivity implements
78 OnNavigationListener, OnClickListener {
79 private ArrayAdapter<String> mDirectories;
80 private DataStorageManager mStorageManager;
81 private FileListFragment mFileList;
82 private OCFile mCurrentDir;
83 private String[] mDirs = null;
84
85 private SyncBroadcastReceiver syncBroadcastRevceiver;
86
87 private static final String KEY_DIR_ARRAY = "DIR_ARRAY";
88 private static final String KEY_CURRENT_DIR = "DIR";
89
90 private static final int DIALOG_SETUP_ACCOUNT = 0;
91 private static final int DIALOG_CREATE_DIR = 1;
92 private static final int ACTION_SELECT_FILE = 1;
93
94 @Override
95 public void onCreate(Bundle savedInstanceState) {
96 super.onCreate(savedInstanceState);
97
98 if (!accountsAreSetup()) {
99 showDialog(DIALOG_SETUP_ACCOUNT);
100 return;
101 }
102
103 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
104 setProgressBarIndeterminateVisibility(false);
105
106 if(savedInstanceState != null){
107 mCurrentDir = (OCFile) savedInstanceState.getParcelable(KEY_CURRENT_DIR);
108 }
109
110 setContentView(R.layout.files);
111 }
112
113 @Override
114 public boolean onCreateOptionsMenu(Menu menu) {
115 MenuInflater inflater = getSherlock().getMenuInflater();
116 inflater.inflate(R.menu.menu, menu);
117 return true;
118 }
119
120 @Override
121 public boolean onOptionsItemSelected(MenuItem item) {
122 boolean retval = true;
123 switch (item.getItemId()) {
124 case R.id.createDirectoryItem: {
125 showDialog(DIALOG_CREATE_DIR);
126 break;
127 }
128 case R.id.startSync: {
129 Bundle bundle = new Bundle();
130 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
131 ContentResolver.requestSync(
132 AccountUtils.getCurrentOwnCloudAccount(this),
133 "org.owncloud", bundle);
134 break;
135 }
136 case R.id.action_upload: {
137 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
138 action = action.setType("*/*")
139 .addCategory(Intent.CATEGORY_OPENABLE);
140 startActivityForResult(
141 Intent.createChooser(action, "Upload file from..."),
142 ACTION_SELECT_FILE);
143 break;
144 }
145
146 case android.R.id.home: {
147 Intent i = new Intent(this, AccountSelectActivity.class);
148 startActivity(i);
149 finish();
150 break;
151 }
152 default:
153 retval = false;
154 }
155 return retval;
156 }
157
158 @Override
159 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
160 int i = itemPosition;
161 while (i-- != 0) {
162 onBackPressed();
163 }
164 return true;
165 }
166
167 /**
168 * Called, when the user selected something for uploading
169 */
170 public void onActivityResult(int requestCode, int resultCode, Intent data) {
171 if (resultCode == RESULT_OK) {
172 if (requestCode == ACTION_SELECT_FILE) {
173 Uri selectedImageUri = data.getData();
174
175 String filemanagerstring = selectedImageUri.getPath();
176 String selectedImagePath = getPath(selectedImageUri);
177 String filepath;
178
179 if (selectedImagePath != null)
180 filepath = selectedImagePath;
181 else
182 filepath = filemanagerstring;
183
184 if (filepath == null) {
185 Log.e("FileDisplay", "Couldnt resolve path to file");
186 return;
187 }
188
189 Intent i = new Intent(this, FileUploader.class);
190 i.putExtra(FileUploader.KEY_ACCOUNT,
191 AccountUtils.getCurrentOwnCloudAccount(this));
192 String remotepath = new String();
193 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
194 remotepath += "/" + URLEncoder.encode(mDirectories.getItem(j));
195 }
196 if (!remotepath.endsWith("/"))
197 remotepath += "/";
198 remotepath += URLEncoder.encode(new File(filepath).getName());
199 Log.e("ASD", remotepath + "");
200
201 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
202 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
203 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
204 startService(i);
205 }
206 }
207 }
208
209 @Override
210 public void onBackPressed() {
211 if (mDirectories.getCount() == 1) {
212 finish();
213 return;
214 }
215 popDirname();
216 mFileList.onNavigateUp();
217 mCurrentDir = mFileList.getCurrentFile();
218 }
219
220 @Override
221 protected void onRestoreInstanceState(Bundle savedInstanceState) {
222 super.onRestoreInstanceState(savedInstanceState);
223 // Check, if there are ownCloud accounts
224 if (!accountsAreSetup()) {
225 showDialog(DIALOG_SETUP_ACCOUNT);
226 }
227 mDirs = savedInstanceState.getStringArray(KEY_DIR_ARRAY);
228 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
229 mDirectories.add("/");
230 if (mDirs != null)
231 for (String s : mDirs)
232 mDirectories.insert(s, 0);
233 }
234
235 @Override
236 protected void onSaveInstanceState(Bundle outState) {
237 super.onSaveInstanceState(outState);
238 if(mDirectories != null){
239 mDirs = new String[mDirectories.getCount()-1];
240 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
241 mDirs[i] = mDirectories.getItem(j);
242 }
243 }
244 outState.putStringArray(KEY_DIR_ARRAY, mDirs);
245 outState.putParcelable(KEY_CURRENT_DIR, mCurrentDir);
246 }
247
248 @Override
249 protected void onResume() {
250 super.onResume();
251
252 //TODO: Dialog useless -> get rid of this
253 if (!accountsAreSetup()) {
254 showDialog(DIALOG_SETUP_ACCOUNT);
255 return;
256 }
257
258 // Listen for sync messages
259 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
260 syncBroadcastRevceiver = new SyncBroadcastReceiver();
261 registerReceiver(syncBroadcastRevceiver, syncIntentFilter);
262
263 // Storage manager initialization
264 mStorageManager = new FileDataStorageManager(
265 AccountUtils.getCurrentOwnCloudAccount(this),
266 getContentResolver());
267
268 // File list
269 mFileList = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
270
271 // Figure out what directory to list.
272 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
273 if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)){
274 mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
275 if(!mCurrentDir.isDirectory()){
276 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
277 }
278
279 // Clear intent extra, so rotating the screen will not return us to this directory
280 getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);
281 }
282
283 // Drop-Down navigation and file list restore
284 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
285
286
287 // Given the case we have a file to display:
288 if(mCurrentDir != null){
289 ArrayList<OCFile> files = new ArrayList<OCFile>();
290 OCFile currFile = mCurrentDir;
291 while(currFile != null){
292 files.add(currFile);
293 currFile = mStorageManager.getFileById(currFile.getParentId());
294 }
295
296 // Insert in mDirs
297 mDirs = new String[files.size()];
298 for(int i = files.size() - 1; i >= 0; i--){
299 mDirs[i] = files.get(i).getFileName();
300 }
301 }
302
303 if (mDirs != null) {
304 for (String s : mDirs)
305 mDirectories.add(s);
306 } else {
307 mDirectories.add("/");
308 }
309
310 // Actionbar setup
311 ActionBar action_bar = getSupportActionBar();
312 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
313 action_bar.setDisplayShowTitleEnabled(false);
314 action_bar.setListNavigationCallbacks(mDirectories, this);
315 action_bar.setDisplayHomeAsUpEnabled(true);
316
317 // List dir here
318 mFileList.listDirectory(mCurrentDir);
319 }
320
321 @Override
322 protected void onPause() {
323 super.onPause();
324 if (syncBroadcastRevceiver != null) {
325 unregisterReceiver(syncBroadcastRevceiver);
326 syncBroadcastRevceiver = null;
327 }
328
329 }
330
331 @Override
332 protected Dialog onCreateDialog(int id) {
333 Dialog dialog;
334 AlertDialog.Builder builder;
335 switch (id) {
336 case DIALOG_SETUP_ACCOUNT:
337 builder = new AlertDialog.Builder(this);
338 builder.setTitle(R.string.main_tit_accsetup);
339 builder.setMessage(R.string.main_wrn_accsetup);
340 builder.setCancelable(false);
341 builder.setPositiveButton(android.R.string.ok, this);
342 builder.setNegativeButton(android.R.string.cancel, this);
343 dialog = builder.create();
344 break;
345 case DIALOG_CREATE_DIR: {
346 builder = new Builder(this);
347 final EditText dirNameInput = new EditText(getBaseContext());
348 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
349 builder.setView(dirNameInput);
350 builder.setTitle(R.string.uploader_info_dirname);
351 int typed_color = getResources().getColor(R.color.setup_text_typed);
352 dirNameInput.setTextColor(typed_color);
353
354 builder.setPositiveButton(android.R.string.ok,
355 new OnClickListener() {
356 public void onClick(DialogInterface dialog, int which) {
357 String directoryName = dirNameInput.getText().toString();
358 if (directoryName.trim().length() == 0) {
359 dialog.cancel();
360 return;
361 }
362
363 // Figure out the path where the dir needs to be created
364 String path = mCurrentDir.getRemotePath();
365
366 // Create directory
367 path += directoryName + "/";
368 Thread thread = new Thread(new DirectoryCreator(
369 path, a));
370 thread.start();
371
372 // Save new directory in local database
373 OCFile newDir = new OCFile(path);
374 newDir.setMimetype("DIR");
375 newDir.setParentId(mCurrentDir.getFileId());
376 mStorageManager.saveFile(newDir);
377
378 // Display the new folder right away
379 dialog.dismiss();
380 mFileList.listDirectory(mCurrentDir);
381 }
382 });
383 builder.setNegativeButton(R.string.common_cancel,
384 new OnClickListener() {
385 public void onClick(DialogInterface dialog, int which) {
386 dialog.cancel();
387 }
388 });
389 dialog = builder.create();
390 break;
391 }
392 default:
393 dialog = null;
394 }
395
396 return dialog;
397 }
398
399
400 /**
401 * Responds to the "There are no ownCloud Accounts setup" dialog
402 * TODO: Dialog is 100% useless -> Remove
403 */
404 @Override
405 public void onClick(DialogInterface dialog, int which) {
406 // In any case - we won't need it anymore
407 dialog.dismiss();
408 switch (which) {
409 case DialogInterface.BUTTON_POSITIVE:
410 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
411 intent.putExtra("authorities",
412 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
413 startActivity(intent);
414 break;
415 case DialogInterface.BUTTON_NEGATIVE:
416 finish();
417 }
418
419 }
420
421 /**
422 * Translates a content URI of an image to a physical path
423 * on the disk
424 * @param uri The URI to resolve
425 * @return The path to the image or null if it could not be found
426 */
427 public String getPath(Uri uri) {
428 String[] projection = { MediaStore.Images.Media.DATA };
429 Cursor cursor = managedQuery(uri, projection, null, null, null);
430 if (cursor != null) {
431 int column_index = cursor
432 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
433 cursor.moveToFirst();
434 return cursor.getString(column_index);
435 }
436 return null;
437 }
438
439 /**
440 * Pushes a directory to the drop down list
441 * @param directory to push
442 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
443 */
444 public void pushDirname(OCFile directory) {
445 if(!directory.isDirectory()){
446 throw new IllegalArgumentException("Only directories may be pushed!");
447 }
448 mDirectories.insert(directory.getFileName(), 0);
449 mCurrentDir = directory;
450 }
451
452 /**
453 * Pops a directory name from the drop down list
454 * @return True, unless the stack is empty
455 */
456 public boolean popDirname() {
457 mDirectories.remove(mDirectories.getItem(0));
458 return !mDirectories.isEmpty();
459 }
460
461 /**
462 * Checks, whether or not there are any ownCloud accounts setup.
463 *
464 * @return true, if there is at least one account.
465 */
466 private boolean accountsAreSetup() {
467 AccountManager accMan = AccountManager.get(this);
468 Account[] accounts = accMan
469 .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
470 return accounts.length > 0;
471 }
472
473 private class DirectoryCreator implements Runnable {
474 private String mTargetPath;
475 private Account mAccount;
476 private AccountManager mAm;
477
478 public DirectoryCreator(String targetPath, Account account) {
479 mTargetPath = targetPath;
480 mAccount = account;
481 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
482 }
483
484 @Override
485 public void run() {
486 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
487 mAccount, AccountAuthenticator.KEY_OC_URL)));
488
489 String username = mAccount.name.substring(0,
490 mAccount.name.lastIndexOf('@'));
491 String password = mAm.getPassword(mAccount);
492
493 wdc.setCredentials(username, password);
494 wdc.allowUnsignedCertificates();
495 wdc.createDirectory(mTargetPath);
496 }
497
498 }
499
500 // Custom array adapter to override text colors
501 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
502
503 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
504 super(ctx, view);
505 }
506
507 public View getView(int position, View convertView, ViewGroup parent) {
508 View v = super.getView(position, convertView, parent);
509
510 ((TextView) v).setTextColor(getResources().getColorStateList(
511 android.R.color.white));
512 return v;
513 }
514
515 public View getDropDownView(int position, View convertView,
516 ViewGroup parent) {
517 View v = super.getDropDownView(position, convertView, parent);
518
519 ((TextView) v).setTextColor(getResources().getColorStateList(
520 android.R.color.white));
521
522 return v;
523 }
524
525 }
526
527 private class SyncBroadcastReceiver extends BroadcastReceiver {
528 /**
529 * {@link BroadcastReceiver} to enable syncing feedback in UI
530 */
531 @Override
532 public void onReceive(Context context, Intent intent) {
533 boolean inProgress = intent.getBooleanExtra(
534 FileSyncService.IN_PROGRESS, false);
535 String account_name = intent
536 .getStringExtra(FileSyncService.ACCOUNT_NAME);
537 Log.d("FileDisplay", "sync of account " + account_name
538 + " is in_progress: " + inProgress);
539 setProgressBarIndeterminateVisibility(inProgress);
540 if (!inProgress) {
541 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
542 .findFragmentById(R.id.fileList);
543 if (fileListFramgent != null)
544 fileListFramgent.listDirectory();
545 }
546 }
547
548 }
549
550 }