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