e8f9151e779dd3e03195b56de9994146d4c94469
[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.util.ArrayList;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.app.AlertDialog;
27 import android.app.AlertDialog.Builder;
28 import android.app.Dialog;
29 import android.content.BroadcastReceiver;
30 import android.content.ContentResolver;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.DialogInterface.OnClickListener;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.pm.PackageInfo;
37 import android.content.pm.PackageManager.NameNotFoundException;
38 import android.database.Cursor;
39 import android.net.Uri;
40 import android.os.Bundle;
41 import android.provider.MediaStore;
42 import android.util.Log;
43 import android.view.View;
44 import android.view.ViewGroup;
45 import android.widget.ArrayAdapter;
46 import android.widget.EditText;
47 import android.widget.TextView;
48
49 import com.actionbarsherlock.app.ActionBar;
50 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
51 import com.actionbarsherlock.app.SherlockFragmentActivity;
52 import com.actionbarsherlock.view.Menu;
53 import com.actionbarsherlock.view.MenuInflater;
54 import com.actionbarsherlock.view.MenuItem;
55 import com.actionbarsherlock.view.Window;
56
57 import eu.alefzero.owncloud.AccountUtils;
58 import eu.alefzero.owncloud.CrashHandler;
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, android.view.View.OnClickListener {
79
80 private ArrayAdapter<String> mDirectories;
81 private OCFile mCurrentDir;
82 private String[] mDirs = null;
83
84 private DataStorageManager mStorageManager;
85 private SyncBroadcastReceiver syncBroadcastReceiver;
86
87 private View mLayoutView = null;
88 private FileListFragment mFileList;
89
90 private static final String KEY_DIR_ARRAY = "DIR_ARRAY";
91 private static final String KEY_CURRENT_DIR = "DIR";
92
93 private static final int DIALOG_SETUP_ACCOUNT = 0;
94 private static final int DIALOG_CREATE_DIR = 1;
95 private static final int DIALOG_ABOUT_APP = 2;
96
97 private static final int ACTION_SELECT_FILE = 1;
98 //private static final int ACTION_CREATE_FIRST_ACCOUNT = 2; dvelasco: WIP
99
100 @Override
101 public void onCreate(Bundle savedInstanceState) {
102 Log.i(getClass().toString(), "onCreate() start");
103 super.onCreate(savedInstanceState);
104
105 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
106 setSupportProgressBarIndeterminateVisibility(false);
107
108 Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
109
110 if(savedInstanceState != null){
111 mCurrentDir = (OCFile) savedInstanceState.getParcelable(KEY_CURRENT_DIR); // this is never saved with this key :S
112 }
113
114 mLayoutView = getLayoutInflater().inflate(R.layout.files, null); // always inflate this at onCreate() ; just once!
115
116 if (AccountUtils.accountsAreSetup(this)) {
117 setContentView(mLayoutView);
118
119 } else {
120 setContentView(R.layout.no_account_available);
121 setProgressBarIndeterminateVisibility(false);
122 getSupportActionBar().setNavigationMode(ActionBar.DISPLAY_SHOW_TITLE);
123 findViewById(R.id.setup_account).setOnClickListener(this);
124 }
125
126 Log.i(getClass().toString(), "onCreate() end");
127 }
128
129 @Override
130 public boolean onCreateOptionsMenu(Menu menu) {
131 MenuInflater inflater = getSherlock().getMenuInflater();
132 inflater.inflate(R.menu.menu, menu);
133 return true;
134 }
135
136 @Override
137 public boolean onOptionsItemSelected(MenuItem item) {
138 boolean retval = true;
139 switch (item.getItemId()) {
140 case R.id.createDirectoryItem: {
141 showDialog(DIALOG_CREATE_DIR);
142 break;
143 }
144 case R.id.startSync: {
145 Bundle bundle = new Bundle();
146 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
147 ContentResolver.requestSync(
148 AccountUtils.getCurrentOwnCloudAccount(this),
149 "org.owncloud", bundle);
150 break;
151 }
152 case R.id.action_upload: {
153 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
154 action = action.setType("*/*")
155 .addCategory(Intent.CATEGORY_OPENABLE);
156 startActivityForResult(
157 Intent.createChooser(action, "Upload file from..."),
158 ACTION_SELECT_FILE);
159 break;
160 }
161 case R.id.action_settings: {
162 Intent settingsIntent = new Intent(this, Preferences.class);
163 startActivity(settingsIntent);
164 break;
165 }
166 case R.id.about_app : {
167 showDialog(DIALOG_ABOUT_APP);
168 break;
169 }
170 case android.R.id.home: {
171 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
172 onBackPressed();
173 }
174 break;
175 }
176 default:
177 retval = false;
178 }
179 return retval;
180 }
181
182 @Override
183 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
184 int i = itemPosition;
185 while (i-- != 0) {
186 onBackPressed();
187 }
188 return true;
189 }
190
191 /**
192 * Called, when the user selected something for uploading
193 */
194 public void onActivityResult(int requestCode, int resultCode, Intent data) {
195 if (requestCode == ACTION_SELECT_FILE) {
196 if (resultCode == RESULT_OK) {
197 Uri selectedImageUri = data.getData();
198
199 String filemanagerstring = selectedImageUri.getPath();
200 String selectedImagePath = getPath(selectedImageUri);
201 String filepath;
202
203 if (selectedImagePath != null)
204 filepath = selectedImagePath;
205 else
206 filepath = filemanagerstring;
207
208 if (filepath == null) {
209 Log.e("FileDisplay", "Couldnt resolve path to file");
210 return;
211 }
212
213 Intent i = new Intent(this, FileUploader.class);
214 i.putExtra(FileUploader.KEY_ACCOUNT,
215 AccountUtils.getCurrentOwnCloudAccount(this));
216 String remotepath = new String();
217 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
218 remotepath += "/" + mDirectories.getItem(j);
219 }
220 if (!remotepath.endsWith("/"))
221 remotepath += "/";
222 remotepath += new File(filepath).getName();
223 remotepath = Uri.encode(remotepath, "/");
224
225 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
226 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
227 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
228 startService(i);
229 }
230
231 }/* dvelasco: WIP - not working as expected ... yet :)
232 else if (requestCode == ACTION_CREATE_FIRST_ACCOUNT) {
233 if (resultCode != RESULT_OK) {
234 finish(); // the user cancelled the AuthenticatorActivity
235 }
236 }*/
237 }
238
239 @Override
240 public void onBackPressed() {
241 if (mDirectories == null || mDirectories.getCount() <= 1) {
242 finish();
243 return;
244 }
245 popDirname();
246 mFileList.onNavigateUp();
247 mCurrentDir = mFileList.getCurrentFile();
248
249 if(mCurrentDir.getParentId() == 0){
250 ActionBar actionBar = getSupportActionBar();
251 actionBar.setDisplayHomeAsUpEnabled(false);
252 }
253 }
254
255 @Override
256 protected void onRestoreInstanceState(Bundle savedInstanceState) {
257 Log.i(getClass().toString(), "onRestoreInstanceState() start");
258 super.onRestoreInstanceState(savedInstanceState);
259 mDirs = savedInstanceState.getStringArray(KEY_DIR_ARRAY);
260 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
261 mDirectories.add("/");
262 if (mDirs != null)
263 for (String s : mDirs)
264 mDirectories.insert(s, 0);
265 mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
266 Log.i(getClass().toString(), "onRestoreInstanceState() end");
267 }
268
269 @Override
270 protected void onSaveInstanceState(Bundle outState) {
271 Log.i(getClass().toString(), "onSaveInstanceState() start");
272 super.onSaveInstanceState(outState);
273 if(mDirectories != null && mDirectories.getCount() != 0){
274 mDirs = new String[mDirectories.getCount()-1];
275 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
276 mDirs[i] = mDirectories.getItem(j);
277 }
278 }
279 outState.putStringArray(KEY_DIR_ARRAY, mDirs);
280 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
281 Log.i(getClass().toString(), "onSaveInstanceState() end");
282 }
283
284 @Override
285 protected void onResume() {
286 Log.i(getClass().toString(), "onResume() start");
287 super.onResume();
288
289 if (!AccountUtils.accountsAreSetup(this)) {
290 /*Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
291 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
292 //startActivity(intent);
293 startActivityForResult(intent, ACTION_CREATE_FIRST_ACCOUNT);*/
294
295 } else { // at least an account exist: normal operation
296
297 // set the layout only if it couldn't be set in onCreate
298 if (findViewById(R.id.file_list_view) == null)
299 setContentView(mLayoutView);
300
301 // Listen for sync messages
302 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
303 syncBroadcastReceiver = new SyncBroadcastReceiver();
304 registerReceiver(syncBroadcastReceiver, syncIntentFilter);
305
306 // Storage manager initialization
307 mStorageManager = new FileDataStorageManager(
308 AccountUtils.getCurrentOwnCloudAccount(this),
309 getContentResolver());
310
311 // File list
312 mFileList = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
313
314 // Figure out what directory to list.
315 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
316 if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)){
317 mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
318 if(mCurrentDir != null && !mCurrentDir.isDirectory()){
319 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
320 }
321
322 // Clear intent extra, so rotating the screen will not return us to this directory
323 getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);
324 }
325
326 if (mCurrentDir == null)
327 mCurrentDir = mStorageManager.getFileByPath("/");
328
329 // Drop-Down navigation and file list restore
330 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
331
332
333 // Given the case we have a file to display:
334 if(mCurrentDir != null){
335 ArrayList<OCFile> files = new ArrayList<OCFile>();
336 OCFile currFile = mCurrentDir;
337 while(currFile != null){
338 files.add(currFile);
339 currFile = mStorageManager.getFileById(currFile.getParentId());
340 }
341
342 // Insert in mDirs
343 mDirs = new String[files.size()];
344 for(int i = files.size() - 1; i >= 0; i--){
345 mDirs[i] = files.get(i).getFileName();
346 }
347 }
348
349 if (mDirs != null) {
350 for (String s : mDirs)
351 mDirectories.add(s);
352 } else {
353 mDirectories.add("/");
354 }
355
356 // Actionbar setup
357 ActionBar action_bar = getSupportActionBar();
358 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
359 action_bar.setDisplayShowTitleEnabled(false);
360 action_bar.setListNavigationCallbacks(mDirectories, this);
361 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
362 action_bar.setDisplayHomeAsUpEnabled(true);
363 } else {
364 action_bar.setDisplayHomeAsUpEnabled(false);
365 }
366
367 // List dir here
368 mFileList.listDirectory(mCurrentDir);
369 }
370 Log.i(getClass().toString(), "onResume() end");
371 }
372
373 @Override
374 protected void onPause() {
375 Log.i(getClass().toString(), "onPause() start");
376 super.onPause();
377 if (syncBroadcastReceiver != null) {
378 unregisterReceiver(syncBroadcastReceiver);
379 syncBroadcastReceiver = null;
380 }
381 getIntent().putExtra(FileDetailFragment.EXTRA_FILE, mCurrentDir);
382 Log.i(getClass().toString(), "onPause() end");
383 }
384
385 @Override
386 protected Dialog onCreateDialog(int id) {
387 Dialog dialog = null;
388 AlertDialog.Builder builder;
389 switch (id) {
390 case DIALOG_SETUP_ACCOUNT:
391 builder = new AlertDialog.Builder(this);
392 builder.setTitle(R.string.main_tit_accsetup);
393 builder.setMessage(R.string.main_wrn_accsetup);
394 builder.setCancelable(false);
395 builder.setPositiveButton(android.R.string.ok, this);
396 builder.setNegativeButton(android.R.string.cancel, this);
397 dialog = builder.create();
398 break;
399 case DIALOG_ABOUT_APP: {
400 builder = new AlertDialog.Builder(this);
401 builder.setTitle("About");
402 PackageInfo pkg;
403 try {
404 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
405 builder.setMessage("ownCloud android client\n\nversion: " + pkg.versionName );
406 builder.setIcon(android.R.drawable.ic_menu_info_details);
407 dialog = builder.create();
408 } catch (NameNotFoundException e) {
409 builder = null;
410 dialog = null;
411 e.printStackTrace();
412 }
413 break;
414 }
415 case DIALOG_CREATE_DIR: {
416 builder = new Builder(this);
417 final EditText dirNameInput = new EditText(getBaseContext());
418 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
419 builder.setView(dirNameInput);
420 builder.setTitle(R.string.uploader_info_dirname);
421 int typed_color = getResources().getColor(R.color.setup_text_typed);
422 dirNameInput.setTextColor(typed_color);
423 builder.setPositiveButton(android.R.string.ok,
424 new OnClickListener() {
425 public void onClick(DialogInterface dialog, int which) {
426 String directoryName = dirNameInput.getText().toString();
427 if (directoryName.trim().length() == 0) {
428 dialog.cancel();
429 return;
430 }
431
432 // Figure out the path where the dir needs to be created
433 String path;
434 if (mCurrentDir == null) {
435 // this is just a patch; we should ensure that mCurrentDir never is null
436 if (!mStorageManager.fileExists("/")) {
437 OCFile file = new OCFile("/");
438 mStorageManager.saveFile(file);
439 }
440 mCurrentDir = mStorageManager.getFileByPath("/");
441 }
442 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
443
444 // Create directory
445 path += Uri.encode(directoryName) + "/";
446 Thread thread = new Thread(new DirectoryCreator(path, a));
447 thread.start();
448
449 // Save new directory in local database
450 OCFile newDir = new OCFile(path);
451 newDir.setMimetype("DIR");
452 newDir.setParentId(mCurrentDir.getFileId());
453 mStorageManager.saveFile(newDir);
454
455 // Display the new folder right away
456 dialog.dismiss();
457 mFileList.listDirectory(mCurrentDir);
458 }
459 });
460 builder.setNegativeButton(R.string.common_cancel,
461 new OnClickListener() {
462 public void onClick(DialogInterface dialog, int which) {
463 dialog.cancel();
464 }
465 });
466 dialog = builder.create();
467 break;
468 }
469 default:
470 dialog = null;
471 }
472
473 return dialog;
474 }
475
476
477 /**
478 * Responds to the "There are no ownCloud Accounts setup" dialog
479 * TODO: Dialog is 100% useless -> Remove
480 */
481 @Override
482 public void onClick(DialogInterface dialog, int which) {
483 // In any case - we won't need it anymore
484 dialog.dismiss();
485 switch (which) {
486 case DialogInterface.BUTTON_POSITIVE:
487 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
488 intent.putExtra("authorities",
489 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
490 startActivity(intent);
491 break;
492 case DialogInterface.BUTTON_NEGATIVE:
493 finish();
494 }
495
496 }
497
498 /**
499 * Translates a content URI of an image to a physical path
500 * on the disk
501 * @param uri The URI to resolve
502 * @return The path to the image or null if it could not be found
503 */
504 public String getPath(Uri uri) {
505 String[] projection = { MediaStore.Images.Media.DATA };
506 Cursor cursor = managedQuery(uri, projection, null, null, null);
507 if (cursor != null) {
508 int column_index = cursor
509 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
510 cursor.moveToFirst();
511 return cursor.getString(column_index);
512 }
513 return null;
514 }
515
516 /**
517 * Pushes a directory to the drop down list
518 * @param directory to push
519 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
520 */
521 public void pushDirname(OCFile directory) {
522 if(!directory.isDirectory()){
523 throw new IllegalArgumentException("Only directories may be pushed!");
524 }
525 mDirectories.insert(directory.getFileName(), 0);
526 mCurrentDir = directory;
527 }
528
529 /**
530 * Pops a directory name from the drop down list
531 * @return True, unless the stack is empty
532 */
533 public boolean popDirname() {
534 mDirectories.remove(mDirectories.getItem(0));
535 return !mDirectories.isEmpty();
536 }
537
538 private class DirectoryCreator implements Runnable {
539 private String mTargetPath;
540 private Account mAccount;
541 private AccountManager mAm;
542
543 public DirectoryCreator(String targetPath, Account account) {
544 mTargetPath = targetPath;
545 mAccount = account;
546 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
547 }
548
549 @Override
550 public void run() {
551 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
552 mAccount, AccountAuthenticator.KEY_OC_URL)));
553
554 String username = mAccount.name.substring(0,
555 mAccount.name.lastIndexOf('@'));
556 String password = mAm.getPassword(mAccount);
557
558 wdc.setCredentials(username, password);
559 wdc.allowSelfsignedCertificates();
560 wdc.createDirectory(mTargetPath);
561 }
562
563 }
564
565 // Custom array adapter to override text colors
566 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
567
568 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
569 super(ctx, view);
570 }
571
572 public View getView(int position, View convertView, ViewGroup parent) {
573 View v = super.getView(position, convertView, parent);
574
575 ((TextView) v).setTextColor(getResources().getColorStateList(
576 android.R.color.white));
577 return v;
578 }
579
580 public View getDropDownView(int position, View convertView,
581 ViewGroup parent) {
582 View v = super.getDropDownView(position, convertView, parent);
583
584 ((TextView) v).setTextColor(getResources().getColorStateList(
585 android.R.color.white));
586
587 return v;
588 }
589
590 }
591
592 private class SyncBroadcastReceiver extends BroadcastReceiver {
593 /**
594 * {@link BroadcastReceiver} to enable syncing feedback in UI
595 */
596 @Override
597 public void onReceive(Context context, Intent intent) {
598 boolean inProgress = intent.getBooleanExtra(
599 FileSyncService.IN_PROGRESS, false);
600 String account_name = intent
601 .getStringExtra(FileSyncService.ACCOUNT_NAME);
602 Log.d("FileDisplay", "sync of account " + account_name
603 + " is in_progress: " + inProgress);
604 setSupportProgressBarIndeterminateVisibility(inProgress);
605 if (!inProgress) {
606 FileListFragment fileListFragment = (FileListFragment) getSupportFragmentManager()
607 .findFragmentById(R.id.fileList);
608 if (fileListFragment != null)
609 fileListFragment.listDirectory();
610 }
611 }
612
613 }
614
615 @Override
616 public void onClick(View v) {
617 if (v.getId() == R.id.setup_account) {
618 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
619 intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
620 startActivity(intent);
621 }
622 }
623
624 public DataStorageManager getStorageManager() {
625 return mStorageManager;
626 }
627 }