b08c3ab6e653214903816a1cceb65b201461cf57
[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 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 }
267
268 @Override
269 protected void onSaveInstanceState(Bundle outState) {
270 super.onSaveInstanceState(outState);
271 if(mDirectories != null && mDirectories.getCount() != 0){
272 mDirs = new String[mDirectories.getCount()-1];
273 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
274 mDirs[i] = mDirectories.getItem(j);
275 }
276 }
277 outState.putStringArray(KEY_DIR_ARRAY, mDirs);
278 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
279 }
280
281 @Override
282 protected void onResume() {
283 super.onResume();
284
285 if (accountsAreSetup()) {
286
287 setContentView(mLayoutView); // this should solve the crash by repeated inflating in big screens (DROIDCLOUD-27)
288
289 // Listen for sync messages
290 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
291 syncBroadcastRevceiver = new SyncBroadcastReceiver();
292 registerReceiver(syncBroadcastRevceiver, syncIntentFilter);
293
294 // Storage manager initialization
295 mStorageManager = new FileDataStorageManager(
296 AccountUtils.getCurrentOwnCloudAccount(this),
297 getContentResolver());
298
299 // File list
300 mFileList = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
301
302 // Figure out what directory to list.
303 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
304 if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)){
305 mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
306 if(mCurrentDir != null && !mCurrentDir.isDirectory()){
307 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
308 }
309
310 // Clear intent extra, so rotating the screen will not return us to this directory
311 getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);
312 } else {
313 mCurrentDir = mStorageManager.getFileByPath("/");
314 }
315
316 // Drop-Down navigation and file list restore
317 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
318
319
320 // Given the case we have a file to display:
321 if(mCurrentDir != null){
322 ArrayList<OCFile> files = new ArrayList<OCFile>();
323 OCFile currFile = mCurrentDir;
324 while(currFile != null){
325 files.add(currFile);
326 currFile = mStorageManager.getFileById(currFile.getParentId());
327 }
328
329 // Insert in mDirs
330 mDirs = new String[files.size()];
331 for(int i = files.size() - 1; i >= 0; i--){
332 mDirs[i] = files.get(i).getFileName();
333 }
334 }
335
336 if (mDirs != null) {
337 for (String s : mDirs)
338 mDirectories.add(s);
339 } else {
340 mDirectories.add("/");
341 }
342
343 // Actionbar setup
344 ActionBar action_bar = getSupportActionBar();
345 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
346 action_bar.setDisplayShowTitleEnabled(false);
347 action_bar.setListNavigationCallbacks(mDirectories, this);
348 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
349 action_bar.setDisplayHomeAsUpEnabled(true);
350 } else {
351 action_bar.setDisplayHomeAsUpEnabled(false);
352 }
353
354 // List dir here
355 mFileList.listDirectory(mCurrentDir);
356 }
357 }
358
359 @Override
360 protected void onPause() {
361 super.onPause();
362 if (syncBroadcastRevceiver != null) {
363 unregisterReceiver(syncBroadcastRevceiver);
364 syncBroadcastRevceiver = null;
365 }
366 getIntent().putExtra(FileDetailFragment.EXTRA_FILE, mCurrentDir);
367 }
368
369 @Override
370 protected Dialog onCreateDialog(int id) {
371 Dialog dialog = null;
372 AlertDialog.Builder builder;
373 switch (id) {
374 case DIALOG_SETUP_ACCOUNT:
375 builder = new AlertDialog.Builder(this);
376 builder.setTitle(R.string.main_tit_accsetup);
377 builder.setMessage(R.string.main_wrn_accsetup);
378 builder.setCancelable(false);
379 builder.setPositiveButton(android.R.string.ok, this);
380 builder.setNegativeButton(android.R.string.cancel, this);
381 dialog = builder.create();
382 break;
383 case DIALOG_ABOUT_APP: {
384 builder = new AlertDialog.Builder(this);
385 builder.setTitle("About");
386 PackageInfo pkg;
387 try {
388 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
389 builder.setMessage("ownCloud android client\n\nversion: " + pkg.versionName );
390 builder.setIcon(android.R.drawable.ic_menu_info_details);
391 dialog = builder.create();
392 } catch (NameNotFoundException e) {
393 builder = null;
394 dialog = null;
395 e.printStackTrace();
396 }
397 break;
398 }
399 case DIALOG_CREATE_DIR: {
400 builder = new Builder(this);
401 final EditText dirNameInput = new EditText(getBaseContext());
402 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
403 builder.setView(dirNameInput);
404 builder.setTitle(R.string.uploader_info_dirname);
405 int typed_color = getResources().getColor(R.color.setup_text_typed);
406 dirNameInput.setTextColor(typed_color);
407 builder.setPositiveButton(android.R.string.ok,
408 new OnClickListener() {
409 public void onClick(DialogInterface dialog, int which) {
410 String directoryName = dirNameInput.getText().toString();
411 if (directoryName.trim().length() == 0) {
412 dialog.cancel();
413 return;
414 }
415
416 // Figure out the path where the dir needs to be created
417 String path;
418 if (mCurrentDir == null) {
419 if (!mStorageManager.fileExists("/")) {
420 OCFile file = new OCFile("/");
421 mStorageManager.saveFile(file);
422 mCurrentDir = mStorageManager.getFileByPath("/");
423 } else {
424 Log.wtf("FileDisplay", "OMG NO!");
425 return;
426 }
427 }
428 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
429
430 // Create directory
431 path += directoryName + "/";
432 Thread thread = new Thread(new DirectoryCreator(path, a));
433 thread.start();
434
435 // Save new directory in local database
436 OCFile newDir = new OCFile(path);
437 newDir.setMimetype("DIR");
438 newDir.setParentId(mCurrentDir.getFileId());
439 mStorageManager.saveFile(newDir);
440
441 // Display the new folder right away
442 dialog.dismiss();
443 mFileList.listDirectory(mCurrentDir);
444 }
445 });
446 builder.setNegativeButton(R.string.common_cancel,
447 new OnClickListener() {
448 public void onClick(DialogInterface dialog, int which) {
449 dialog.cancel();
450 }
451 });
452 dialog = builder.create();
453 break;
454 }
455 default:
456 dialog = null;
457 }
458
459 return dialog;
460 }
461
462
463 /**
464 * Responds to the "There are no ownCloud Accounts setup" dialog
465 * TODO: Dialog is 100% useless -> Remove
466 */
467 @Override
468 public void onClick(DialogInterface dialog, int which) {
469 // In any case - we won't need it anymore
470 dialog.dismiss();
471 switch (which) {
472 case DialogInterface.BUTTON_POSITIVE:
473 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
474 intent.putExtra("authorities",
475 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
476 startActivity(intent);
477 break;
478 case DialogInterface.BUTTON_NEGATIVE:
479 finish();
480 }
481
482 }
483
484 /**
485 * Translates a content URI of an image to a physical path
486 * on the disk
487 * @param uri The URI to resolve
488 * @return The path to the image or null if it could not be found
489 */
490 public String getPath(Uri uri) {
491 String[] projection = { MediaStore.Images.Media.DATA };
492 Cursor cursor = managedQuery(uri, projection, null, null, null);
493 if (cursor != null) {
494 int column_index = cursor
495 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
496 cursor.moveToFirst();
497 return cursor.getString(column_index);
498 }
499 return null;
500 }
501
502 /**
503 * Pushes a directory to the drop down list
504 * @param directory to push
505 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
506 */
507 public void pushDirname(OCFile directory) {
508 if(!directory.isDirectory()){
509 throw new IllegalArgumentException("Only directories may be pushed!");
510 }
511 mDirectories.insert(directory.getFileName(), 0);
512 mCurrentDir = directory;
513 }
514
515 /**
516 * Pops a directory name from the drop down list
517 * @return True, unless the stack is empty
518 */
519 public boolean popDirname() {
520 mDirectories.remove(mDirectories.getItem(0));
521 return !mDirectories.isEmpty();
522 }
523
524 /**
525 * Checks, whether or not there are any ownCloud accounts setup.
526 *
527 * @return true, if there is at least one account.
528 */
529 private boolean accountsAreSetup() {
530 AccountManager accMan = AccountManager.get(this);
531 Account[] accounts = accMan
532 .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
533 return accounts.length > 0;
534 }
535
536 private class DirectoryCreator implements Runnable {
537 private String mTargetPath;
538 private Account mAccount;
539 private AccountManager mAm;
540
541 public DirectoryCreator(String targetPath, Account account) {
542 mTargetPath = targetPath;
543 mAccount = account;
544 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
545 }
546
547 @Override
548 public void run() {
549 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
550 mAccount, AccountAuthenticator.KEY_OC_URL)));
551
552 String username = mAccount.name.substring(0,
553 mAccount.name.lastIndexOf('@'));
554 String password = mAm.getPassword(mAccount);
555
556 wdc.setCredentials(username, password);
557 wdc.allowSelfsignedCertificates();
558 wdc.createDirectory(mTargetPath);
559 }
560
561 }
562
563 // Custom array adapter to override text colors
564 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
565
566 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
567 super(ctx, view);
568 }
569
570 public View getView(int position, View convertView, ViewGroup parent) {
571 View v = super.getView(position, convertView, parent);
572
573 ((TextView) v).setTextColor(getResources().getColorStateList(
574 android.R.color.white));
575 return v;
576 }
577
578 public View getDropDownView(int position, View convertView,
579 ViewGroup parent) {
580 View v = super.getDropDownView(position, convertView, parent);
581
582 ((TextView) v).setTextColor(getResources().getColorStateList(
583 android.R.color.white));
584
585 return v;
586 }
587
588 }
589
590 private class SyncBroadcastReceiver extends BroadcastReceiver {
591 /**
592 * {@link BroadcastReceiver} to enable syncing feedback in UI
593 */
594 @Override
595 public void onReceive(Context context, Intent intent) {
596 boolean inProgress = intent.getBooleanExtra(
597 FileSyncService.IN_PROGRESS, false);
598 String account_name = intent
599 .getStringExtra(FileSyncService.ACCOUNT_NAME);
600 Log.d("FileDisplay", "sync of account " + account_name
601 + " is in_progress: " + inProgress);
602 setProgressBarIndeterminateVisibility(inProgress);
603 if (!inProgress) {
604 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
605 .findFragmentById(R.id.fileList);
606 if (fileListFramgent != null)
607 fileListFramgent.listDirectory();
608 }
609 }
610
611 }
612
613 @Override
614 public void onClick(View v) {
615 if (v.getId() == R.id.setup_account) {
616 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
617 intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
618 startActivity(intent);
619 }
620 }
621
622 public DataStorageManager getStorageManager() {
623 return mStorageManager;
624 }
625 }