93cf6495a2553853f1dcfc7b91a17f180022616e
[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.File;
22 import java.net.URLEncoder;
23 import java.util.ArrayList;
24
25 import android.accounts.Account;
26 import android.accounts.AccountManager;
27 import android.app.AlertDialog;
28 import android.app.AlertDialog.Builder;
29 import android.app.Dialog;
30 import android.content.BroadcastReceiver;
31 import android.content.ContentResolver;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.DialogInterface.OnClickListener;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.database.Cursor;
38 import android.net.Uri;
39 import android.os.Bundle;
40 import android.provider.MediaStore;
41 import android.util.Log;
42 import android.view.View;
43 import android.view.ViewGroup;
44 import android.widget.ArrayAdapter;
45 import android.widget.EditText;
46 import android.widget.TextView;
47
48 import com.actionbarsherlock.app.ActionBar;
49 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
50 import com.actionbarsherlock.app.SherlockFragmentActivity;
51 import com.actionbarsherlock.view.Menu;
52 import com.actionbarsherlock.view.MenuInflater;
53 import com.actionbarsherlock.view.MenuItem;
54 import com.actionbarsherlock.view.Window;
55
56 import eu.alefzero.owncloud.AccountUtils;
57 import eu.alefzero.owncloud.R;
58 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
59 import eu.alefzero.owncloud.datamodel.DataStorageManager;
60 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
61 import eu.alefzero.owncloud.datamodel.OCFile;
62 import eu.alefzero.owncloud.files.services.FileUploader;
63 import eu.alefzero.owncloud.syncadapter.FileSyncService;
64 import eu.alefzero.owncloud.ui.fragment.FileDetailFragment;
65 import eu.alefzero.owncloud.ui.fragment.FileListFragment;
66 import eu.alefzero.webdav.WebdavClient;
67
68 /**
69 * Displays, what files the user has available in his ownCloud.
70 *
71 * @author Bartek Przybylski
72 *
73 */
74
75 public class FileDisplayActivity extends SherlockFragmentActivity implements
76 OnNavigationListener, OnClickListener {
77 private ArrayAdapter<String> mDirectories;
78 private DataStorageManager mStorageManager;
79 private FileListFragment mFileList;
80 private OCFile mCurrentDir;
81 private String[] mDirs = null;
82
83 private SyncBroadcastReceiver syncBroadcastRevceiver;
84
85 private static final String KEY_DIR_ARRAY = "DIR_ARRAY";
86 private static final String KEY_CURRENT_DIR = "DIR";
87
88 private static final int DIALOG_SETUP_ACCOUNT = 0;
89 private static final int DIALOG_CREATE_DIR = 1;
90 private static final int ACTION_SELECT_FILE = 1;
91
92 @Override
93 public void onCreate(Bundle savedInstanceState) {
94 super.onCreate(savedInstanceState);
95
96 if (!accountsAreSetup()) {
97 showDialog(DIALOG_SETUP_ACCOUNT);
98 return;
99 }
100
101 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
102 setProgressBarIndeterminateVisibility(false);
103
104 if(savedInstanceState != null){
105 mCurrentDir = (OCFile) savedInstanceState.getParcelable(KEY_CURRENT_DIR);
106 }
107
108 setContentView(R.layout.files);
109 }
110
111 @Override
112 public boolean onCreateOptionsMenu(Menu menu) {
113 MenuInflater inflater = getSherlock().getMenuInflater();
114 inflater.inflate(R.menu.menu, menu);
115 return true;
116 }
117
118 @Override
119 public boolean onOptionsItemSelected(MenuItem item) {
120 boolean retval = true;
121 switch (item.getItemId()) {
122 case R.id.createDirectoryItem: {
123 showDialog(DIALOG_CREATE_DIR);
124 break;
125 }
126 case R.id.startSync: {
127 Bundle bundle = new Bundle();
128 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
129 ContentResolver.requestSync(
130 AccountUtils.getCurrentOwnCloudAccount(this),
131 "org.owncloud", bundle);
132 break;
133 }
134 case R.id.action_upload: {
135 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
136 action = action.setType("*/*")
137 .addCategory(Intent.CATEGORY_OPENABLE);
138 startActivityForResult(
139 Intent.createChooser(action, "Upload file from..."),
140 ACTION_SELECT_FILE);
141 break;
142 }
143 case R.id.action_accounts: {
144 Intent accountIntent = new Intent(this, AccountSelectActivity.class);
145 startActivity(accountIntent);
146 }
147 case android.R.id.home: {
148 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
149 onBackPressed();
150 }
151 break;
152 }
153 default:
154 retval = false;
155 }
156 return retval;
157 }
158
159 @Override
160 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
161 int i = itemPosition;
162 while (i-- != 0) {
163 onBackPressed();
164 }
165 return true;
166 }
167
168 /**
169 * Called, when the user selected something for uploading
170 */
171 public void onActivityResult(int requestCode, int resultCode, Intent data) {
172 if (resultCode == RESULT_OK) {
173 if (requestCode == ACTION_SELECT_FILE) {
174 Uri selectedImageUri = data.getData();
175
176 String filemanagerstring = selectedImageUri.getPath();
177 String selectedImagePath = getPath(selectedImageUri);
178 String filepath;
179
180 if (selectedImagePath != null)
181 filepath = selectedImagePath;
182 else
183 filepath = filemanagerstring;
184
185 if (filepath == null) {
186 Log.e("FileDisplay", "Couldnt resolve path to file");
187 return;
188 }
189
190 Intent i = new Intent(this, FileUploader.class);
191 i.putExtra(FileUploader.KEY_ACCOUNT,
192 AccountUtils.getCurrentOwnCloudAccount(this));
193 String remotepath = new String();
194 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
195 remotepath += "/" + URLEncoder.encode(mDirectories.getItem(j));
196 }
197 if (!remotepath.endsWith("/"))
198 remotepath += "/";
199 remotepath += URLEncoder.encode(new File(filepath).getName());
200 Log.e("ASD", remotepath + "");
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.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 // Check, if there are ownCloud accounts
230 if (!accountsAreSetup()) {
231 showDialog(DIALOG_SETUP_ACCOUNT);
232 }
233 mDirs = savedInstanceState.getStringArray(KEY_DIR_ARRAY);
234 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
235 mDirectories.add("/");
236 if (mDirs != null)
237 for (String s : mDirs)
238 mDirectories.insert(s, 0);
239 }
240
241 @Override
242 protected void onSaveInstanceState(Bundle outState) {
243 super.onSaveInstanceState(outState);
244 if(mDirectories != null){
245 mDirs = new String[mDirectories.getCount()-1];
246 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
247 mDirs[i] = mDirectories.getItem(j);
248 }
249 }
250 outState.putStringArray(KEY_DIR_ARRAY, mDirs);
251 outState.putParcelable(KEY_CURRENT_DIR, mCurrentDir);
252 }
253
254 @Override
255 protected void onResume() {
256 super.onResume();
257
258 //TODO: Dialog useless -> get rid of this
259 if (!accountsAreSetup()) {
260 showDialog(DIALOG_SETUP_ACCOUNT);
261 return;
262 }
263
264 // Listen for sync messages
265 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
266 syncBroadcastRevceiver = new SyncBroadcastReceiver();
267 registerReceiver(syncBroadcastRevceiver, syncIntentFilter);
268
269 // Storage manager initialization
270 mStorageManager = new FileDataStorageManager(
271 AccountUtils.getCurrentOwnCloudAccount(this),
272 getContentResolver());
273
274 // File list
275 mFileList = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
276
277 // Figure out what directory to list.
278 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
279 if(getIntent().hasExtra(FileDetailFragment.EXTRA_FILE)){
280 mCurrentDir = (OCFile) getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
281 if(!mCurrentDir.isDirectory()){
282 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
283 }
284
285 // Clear intent extra, so rotating the screen will not return us to this directory
286 getIntent().removeExtra(FileDetailFragment.EXTRA_FILE);
287 }
288
289 // Drop-Down navigation and file list restore
290 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
291
292
293 // Given the case we have a file to display:
294 if(mCurrentDir != null){
295 ArrayList<OCFile> files = new ArrayList<OCFile>();
296 OCFile currFile = mCurrentDir;
297 while(currFile != null){
298 files.add(currFile);
299 currFile = mStorageManager.getFileById(currFile.getParentId());
300 }
301
302 // Insert in mDirs
303 mDirs = new String[files.size()];
304 for(int i = files.size() - 1; i >= 0; i--){
305 mDirs[i] = files.get(i).getFileName();
306 }
307 }
308
309 if (mDirs != null) {
310 for (String s : mDirs)
311 mDirectories.add(s);
312 } else {
313 mDirectories.add("/");
314 }
315
316 // Actionbar setup
317 ActionBar action_bar = getSupportActionBar();
318 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
319 action_bar.setDisplayShowTitleEnabled(false);
320 action_bar.setListNavigationCallbacks(mDirectories, this);
321 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
322 action_bar.setDisplayHomeAsUpEnabled(true);
323 } else {
324 action_bar.setDisplayHomeAsUpEnabled(false);
325 }
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.allowUnsignedCertificates();
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 }