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