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