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