1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
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.
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.
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/>.
19 package eu
.alefzero
.owncloud
.ui
.activity
;
21 import java
.io
.BufferedReader
;
23 import java
.io
.InputStreamReader
;
24 import java
.lang
.Thread
.UncaughtExceptionHandler
;
25 import java
.util
.ArrayList
;
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
;
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
;
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
;
77 * Displays, what files the user has available in his ownCloud.
79 * @author Bartek Przybylski
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
;
91 private SyncBroadcastReceiver syncBroadcastRevceiver
;
93 private View mLayoutView
= null
;
95 private static final String KEY_DIR_ARRAY
= "DIR_ARRAY";
96 private static final String KEY_CURRENT_DIR
= "DIR";
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;
104 public void onCreate(Bundle savedInstanceState
) {
105 super.onCreate(savedInstanceState
);
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
);
114 Thread
.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
116 if(savedInstanceState
!= null
){
117 mCurrentDir
= (OCFile
) savedInstanceState
.getParcelable(KEY_CURRENT_DIR
);
120 if (findViewById(R
.id
.file_list_view
) == null
)
121 mLayoutView
= getLayoutInflater().inflate(R
.layout
.files
, null
); // always inflate this at onCreate() ; just once!
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);
130 } else if (findViewById(R
.id
.file_list_view
) == null
) {
131 setContentView(mLayoutView
);
137 public boolean onCreateOptionsMenu(Menu menu
) {
138 MenuInflater inflater
= getSherlock().getMenuInflater();
139 inflater
.inflate(R
.menu
.menu
, menu
);
144 public boolean onOptionsItemSelected(MenuItem item
) {
145 boolean retval
= true
;
146 switch (item
.getItemId()) {
147 case R
.id
.createDirectoryItem
: {
148 showDialog(DIALOG_CREATE_DIR
);
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
);
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..."),
168 case R
.id
.action_settings
: {
169 Intent settingsIntent
= new Intent(this, Preferences
.class);
170 startActivity(settingsIntent
);
173 case R
.id
.about_app
: {
174 showDialog(DIALOG_ABOUT_APP
);
177 case android
.R
.id
.home
: {
178 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
190 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
191 int i
= itemPosition
;
199 * Called, when the user selected something for uploading
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();
206 String filemanagerstring
= selectedImageUri
.getPath();
207 String selectedImagePath
= getPath(selectedImageUri
);
210 if (selectedImagePath
!= null
)
211 filepath
= selectedImagePath
;
213 filepath
= filemanagerstring
;
215 if (filepath
== null
) {
216 Log
.e("FileDisplay", "Couldnt resolve path to file");
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
);
227 if (!remotepath
.endsWith("/"))
229 remotepath
+= new File(filepath
).getName();
230 remotepath
= Uri
.encode(remotepath
, "/");
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
);
241 public void onBackPressed() {
242 if (mDirectories
== null
|| mDirectories
.getCount() <= 1) {
247 mFileList
.onNavigateUp();
248 mCurrentDir
= mFileList
.getCurrentFile();
250 if(mCurrentDir
.getParentId() == 0){
251 ActionBar actionBar
= getSupportActionBar();
252 actionBar
.setDisplayHomeAsUpEnabled(false
);
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("/");
263 for (String s
: mDirs
)
264 mDirectories
.insert(s
, 0);
265 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
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
);
277 outState
.putStringArray(KEY_DIR_ARRAY
, mDirs
);
278 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
282 protected void onResume() {
285 if (accountsAreSetup()) {
287 setContentView(mLayoutView
); // this should solve the crash by repeated inflating in big screens (DROIDCLOUD-27)
289 // Listen for sync messages
290 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
291 syncBroadcastRevceiver
= new SyncBroadcastReceiver();
292 registerReceiver(syncBroadcastRevceiver
, syncIntentFilter
);
294 // Storage manager initialization
295 mStorageManager
= new FileDataStorageManager(
296 AccountUtils
.getCurrentOwnCloudAccount(this),
297 getContentResolver());
300 mFileList
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
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());
310 // Clear intent extra, so rotating the screen will not return us to this directory
311 getIntent().removeExtra(FileDetailFragment
.EXTRA_FILE
);
314 if (mCurrentDir
== null
)
315 mCurrentDir
= mStorageManager
.getFileByPath("/");
317 // Drop-Down navigation and file list restore
318 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
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
){
327 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
331 mDirs
= new String
[files
.size()];
332 for(int i
= files
.size() - 1; i
>= 0; i
--){
333 mDirs
[i
] = files
.get(i
).getFileName();
338 for (String s
: mDirs
)
341 mDirectories
.add("/");
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
);
352 action_bar
.setDisplayHomeAsUpEnabled(false
);
356 mFileList
.listDirectory(mCurrentDir
);
361 protected void onPause() {
363 if (syncBroadcastRevceiver
!= null
) {
364 unregisterReceiver(syncBroadcastRevceiver
);
365 syncBroadcastRevceiver
= null
;
367 getIntent().putExtra(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
371 protected Dialog
onCreateDialog(int id
) {
372 Dialog dialog
= null
;
373 AlertDialog
.Builder builder
;
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();
384 case DIALOG_ABOUT_APP
: {
385 builder
= new AlertDialog
.Builder(this);
386 builder
.setTitle("About");
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
) {
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) {
417 // Figure out the path where the dir needs to be created
419 if (mCurrentDir
== null
) {
420 if (!mStorageManager
.fileExists("/")) {
421 OCFile file
= new OCFile("/");
422 mStorageManager
.saveFile(file
);
423 mCurrentDir
= mStorageManager
.getFileByPath("/");
425 Log
.wtf("FileDisplay", "OMG NO!");
429 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
432 path
+= Uri
.encode(directoryName
) + "/";
433 Thread thread
= new Thread(new DirectoryCreator(path
, a
));
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
);
442 // Display the new folder right away
444 mFileList
.listDirectory(mCurrentDir
);
447 builder
.setNegativeButton(R
.string
.common_cancel
,
448 new OnClickListener() {
449 public void onClick(DialogInterface dialog
, int which
) {
453 dialog
= builder
.create();
465 * Responds to the "There are no ownCloud Accounts setup" dialog
466 * TODO: Dialog is 100% useless -> Remove
469 public void onClick(DialogInterface dialog
, int which
) {
470 // In any case - we won't need it anymore
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
);
479 case DialogInterface
.BUTTON_NEGATIVE
:
486 * Translates a content URI of an image to a physical path
488 * @param uri The URI to resolve
489 * @return The path to the image or null if it could not be found
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
);
504 * Pushes a directory to the drop down list
505 * @param directory to push
506 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
508 public void pushDirname(OCFile directory
) {
509 if(!directory
.isDirectory()){
510 throw new IllegalArgumentException("Only directories may be pushed!");
512 mDirectories
.insert(directory
.getFileName(), 0);
513 mCurrentDir
= directory
;
517 * Pops a directory name from the drop down list
518 * @return True, unless the stack is empty
520 public boolean popDirname() {
521 mDirectories
.remove(mDirectories
.getItem(0));
522 return !mDirectories
.isEmpty();
526 * Checks, whether or not there are any ownCloud accounts setup.
528 * @return true, if there is at least one account.
530 private boolean accountsAreSetup() {
531 AccountManager accMan
= AccountManager
.get(this);
532 Account
[] accounts
= accMan
533 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
);
534 return accounts
.length
> 0;
537 private class DirectoryCreator
implements Runnable
{
538 private String mTargetPath
;
539 private Account mAccount
;
540 private AccountManager mAm
;
542 public DirectoryCreator(String targetPath
, Account account
) {
543 mTargetPath
= targetPath
;
545 mAm
= (AccountManager
) getSystemService(ACCOUNT_SERVICE
);
550 WebdavClient wdc
= new WebdavClient(Uri
.parse(mAm
.getUserData(
551 mAccount
, AccountAuthenticator
.KEY_OC_URL
)));
553 String username
= mAccount
.name
.substring(0,
554 mAccount
.name
.lastIndexOf('@'));
555 String password
= mAm
.getPassword(mAccount
);
557 wdc
.setCredentials(username
, password
);
558 wdc
.allowSelfsignedCertificates();
559 wdc
.createDirectory(mTargetPath
);
564 // Custom array adapter to override text colors
565 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
567 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
571 public View
getView(int position
, View convertView
, ViewGroup parent
) {
572 View v
= super.getView(position
, convertView
, parent
);
574 ((TextView
) v
).setTextColor(getResources().getColorStateList(
575 android
.R
.color
.white
));
579 public View
getDropDownView(int position
, View convertView
,
581 View v
= super.getDropDownView(position
, convertView
, parent
);
583 ((TextView
) v
).setTextColor(getResources().getColorStateList(
584 android
.R
.color
.white
));
591 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
593 * {@link BroadcastReceiver} to enable syncing feedback in UI
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
);
605 FileListFragment fileListFramgent
= (FileListFragment
) getSupportFragmentManager()
606 .findFragmentById(R
.id
.fileList
);
607 if (fileListFramgent
!= null
)
608 fileListFramgent
.listDirectory();
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
);
623 public DataStorageManager
getStorageManager() {
624 return mStorageManager
;