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