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