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
.net
.URLEncoder
;
26 import java
.util
.ArrayList
;
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
.content
.pm
.PackageInfo
;
41 import android
.content
.pm
.PackageManager
;
42 import android
.content
.pm
.PackageManager
.NameNotFoundException
;
43 import android
.database
.Cursor
;
44 import android
.net
.Uri
;
45 import android
.os
.Bundle
;
46 import android
.provider
.MediaStore
;
47 import android
.telephony
.TelephonyManager
;
48 import android
.util
.Log
;
49 import android
.view
.View
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ArrayAdapter
;
52 import android
.widget
.CheckedTextView
;
53 import android
.widget
.EditText
;
54 import android
.widget
.TextView
;
56 import com
.actionbarsherlock
.app
.ActionBar
;
57 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
58 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
59 import com
.actionbarsherlock
.view
.Menu
;
60 import com
.actionbarsherlock
.view
.MenuInflater
;
61 import com
.actionbarsherlock
.view
.MenuItem
;
62 import com
.actionbarsherlock
.view
.Window
;
64 import eu
.alefzero
.owncloud
.AccountUtils
;
65 import eu
.alefzero
.owncloud
.CrashHandler
;
66 import eu
.alefzero
.owncloud
.R
;
67 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
68 import eu
.alefzero
.owncloud
.datamodel
.DataStorageManager
;
69 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
70 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
71 import eu
.alefzero
.owncloud
.files
.services
.FileUploader
;
72 import eu
.alefzero
.owncloud
.syncadapter
.FileSyncService
;
73 import eu
.alefzero
.owncloud
.ui
.fragment
.FileDetailFragment
;
74 import eu
.alefzero
.owncloud
.ui
.fragment
.FileListFragment
;
75 import eu
.alefzero
.webdav
.WebdavClient
;
78 * Displays, what files the user has available in his ownCloud.
80 * @author Bartek Przybylski
84 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
85 OnNavigationListener
, OnClickListener
, android
.view
.View
.OnClickListener
{
86 private ArrayAdapter
<String
> mDirectories
;
87 private DataStorageManager mStorageManager
;
88 private FileListFragment mFileList
;
89 private OCFile mCurrentDir
;
90 private String
[] mDirs
= null
;
92 private SyncBroadcastReceiver syncBroadcastRevceiver
;
94 private View mLayoutView
= null
;
96 private static final String KEY_DIR_ARRAY
= "DIR_ARRAY";
97 private static final String KEY_CURRENT_DIR
= "DIR";
99 private static final int DIALOG_SETUP_ACCOUNT
= 0;
100 private static final int DIALOG_CREATE_DIR
= 1;
101 private static final int DIALOG_ABOUT_APP
= 2;
102 private static final int ACTION_SELECT_FILE
= 1;
105 public void onCreate(Bundle savedInstanceState
) {
106 super.onCreate(savedInstanceState
);
108 // TODO: fix hack: workaround for bug in actionbar sherlock
109 // it always shows indeterminate progress bar
110 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
111 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
112 setProgressBarIndeterminateVisibility(false
);
115 Thread
.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
117 if(savedInstanceState
!= null
){
118 mCurrentDir
= (OCFile
) savedInstanceState
.getParcelable(KEY_CURRENT_DIR
);
121 if (findViewById(R
.id
.file_list_view
) == null
)
122 mLayoutView
= getLayoutInflater().inflate(R
.layout
.files
, null
); // always inflate this at onCreate() ; just once!
124 //TODO: Dialog useless -> get rid of this
125 if (!accountsAreSetup()) {
126 setContentView(R
.layout
.no_account_available
);
127 setProgressBarIndeterminateVisibility(false
);
128 getSupportActionBar().setNavigationMode(ActionBar
.DISPLAY_SHOW_TITLE
);
129 findViewById(R
.id
.setup_account
).setOnClickListener(this);
131 } else if (findViewById(R
.id
.file_list_view
) == null
) {
132 setContentView(mLayoutView
);
138 public boolean onCreateOptionsMenu(Menu menu
) {
139 MenuInflater inflater
= getSherlock().getMenuInflater();
140 inflater
.inflate(R
.menu
.menu
, menu
);
145 public boolean onOptionsItemSelected(MenuItem item
) {
146 boolean retval
= true
;
147 switch (item
.getItemId()) {
148 case R
.id
.createDirectoryItem
: {
149 showDialog(DIALOG_CREATE_DIR
);
152 case R
.id
.startSync
: {
153 Bundle bundle
= new Bundle();
154 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
155 ContentResolver
.requestSync(
156 AccountUtils
.getCurrentOwnCloudAccount(this),
157 "org.owncloud", bundle
);
160 case R
.id
.action_upload
: {
161 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
162 action
= action
.setType("*/*")
163 .addCategory(Intent
.CATEGORY_OPENABLE
);
164 startActivityForResult(
165 Intent
.createChooser(action
, "Upload file from..."),
169 case R
.id
.action_settings
: {
170 Intent settingsIntent
= new Intent(this, Preferences
.class);
171 startActivity(settingsIntent
);
174 case R
.id
.about_app
: {
175 showDialog(DIALOG_ABOUT_APP
);
178 case android
.R
.id
.home
: {
179 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
191 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
192 int i
= itemPosition
;
200 * Called, when the user selected something for uploading
202 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
203 if (resultCode
== RESULT_OK
) {
204 if (requestCode
== ACTION_SELECT_FILE
) {
205 Uri selectedImageUri
= data
.getData();
207 String filemanagerstring
= selectedImageUri
.getPath();
208 String selectedImagePath
= getPath(selectedImageUri
);
211 if (selectedImagePath
!= null
)
212 filepath
= selectedImagePath
;
214 filepath
= filemanagerstring
;
216 if (filepath
== null
) {
217 Log
.e("FileDisplay", "Couldnt resolve path to file");
221 Intent i
= new Intent(this, FileUploader
.class);
222 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
223 AccountUtils
.getCurrentOwnCloudAccount(this));
224 String remotepath
= new String();
225 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
226 remotepath
+= "/" + URLEncoder
.encode(mDirectories
.getItem(j
));
228 if (!remotepath
.endsWith("/"))
230 remotepath
+= URLEncoder
.encode(new File(filepath
).getName());
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
);
313 mCurrentDir
= mStorageManager
.getFileByPath("/");
316 // Drop-Down navigation and file list restore
317 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
320 // Given the case we have a file to display:
321 if(mCurrentDir
!= null
){
322 ArrayList
<OCFile
> files
= new ArrayList
<OCFile
>();
323 OCFile currFile
= mCurrentDir
;
324 while(currFile
!= null
){
326 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
330 mDirs
= new String
[files
.size()];
331 for(int i
= files
.size() - 1; i
>= 0; i
--){
332 mDirs
[i
] = files
.get(i
).getFileName();
337 for (String s
: mDirs
)
340 mDirectories
.add("/");
344 ActionBar action_bar
= getSupportActionBar();
345 action_bar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
346 action_bar
.setDisplayShowTitleEnabled(false
);
347 action_bar
.setListNavigationCallbacks(mDirectories
, this);
348 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
349 action_bar
.setDisplayHomeAsUpEnabled(true
);
351 action_bar
.setDisplayHomeAsUpEnabled(false
);
355 mFileList
.listDirectory(mCurrentDir
);
360 protected void onPause() {
362 if (syncBroadcastRevceiver
!= null
) {
363 unregisterReceiver(syncBroadcastRevceiver
);
364 syncBroadcastRevceiver
= null
;
366 getIntent().putExtra(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
370 protected Dialog
onCreateDialog(int id
) {
371 Dialog dialog
= null
;
372 AlertDialog
.Builder builder
;
374 case DIALOG_SETUP_ACCOUNT
:
375 builder
= new AlertDialog
.Builder(this);
376 builder
.setTitle(R
.string
.main_tit_accsetup
);
377 builder
.setMessage(R
.string
.main_wrn_accsetup
);
378 builder
.setCancelable(false
);
379 builder
.setPositiveButton(android
.R
.string
.ok
, this);
380 builder
.setNegativeButton(android
.R
.string
.cancel
, this);
381 dialog
= builder
.create();
383 case DIALOG_ABOUT_APP
: {
384 builder
= new AlertDialog
.Builder(this);
385 builder
.setTitle("About");
388 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
389 builder
.setMessage("ownCloud android client\n\nversion: " + pkg
.versionName
);
390 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
391 dialog
= builder
.create();
392 } catch (NameNotFoundException e
) {
399 case DIALOG_CREATE_DIR
: {
400 builder
= new Builder(this);
401 final EditText dirNameInput
= new EditText(getBaseContext());
402 final Account a
= AccountUtils
.getCurrentOwnCloudAccount(this);
403 builder
.setView(dirNameInput
);
404 builder
.setTitle(R
.string
.uploader_info_dirname
);
405 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
406 dirNameInput
.setTextColor(typed_color
);
407 builder
.setPositiveButton(android
.R
.string
.ok
,
408 new OnClickListener() {
409 public void onClick(DialogInterface dialog
, int which
) {
410 String directoryName
= dirNameInput
.getText().toString();
411 if (directoryName
.trim().length() == 0) {
416 // Figure out the path where the dir needs to be created
417 String path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
420 path
+= directoryName
+ "/";
421 Thread thread
= new Thread(new DirectoryCreator(path
, a
));
424 // Save new directory in local database
425 OCFile newDir
= new OCFile(path
);
426 newDir
.setMimetype("DIR");
427 newDir
.setParentId(mCurrentDir
.getFileId());
428 mStorageManager
.saveFile(newDir
);
430 // Display the new folder right away
432 mFileList
.listDirectory(mCurrentDir
);
435 builder
.setNegativeButton(R
.string
.common_cancel
,
436 new OnClickListener() {
437 public void onClick(DialogInterface dialog
, int which
) {
441 dialog
= builder
.create();
453 * Responds to the "There are no ownCloud Accounts setup" dialog
454 * TODO: Dialog is 100% useless -> Remove
457 public void onClick(DialogInterface dialog
, int which
) {
458 // In any case - we won't need it anymore
461 case DialogInterface
.BUTTON_POSITIVE
:
462 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
463 intent
.putExtra("authorities",
464 new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
465 startActivity(intent
);
467 case DialogInterface
.BUTTON_NEGATIVE
:
474 * Translates a content URI of an image to a physical path
476 * @param uri The URI to resolve
477 * @return The path to the image or null if it could not be found
479 public String
getPath(Uri uri
) {
480 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
481 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
482 if (cursor
!= null
) {
483 int column_index
= cursor
484 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
485 cursor
.moveToFirst();
486 return cursor
.getString(column_index
);
492 * Pushes a directory to the drop down list
493 * @param directory to push
494 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
496 public void pushDirname(OCFile directory
) {
497 if(!directory
.isDirectory()){
498 throw new IllegalArgumentException("Only directories may be pushed!");
500 mDirectories
.insert(directory
.getFileName(), 0);
501 mCurrentDir
= directory
;
505 * Pops a directory name from the drop down list
506 * @return True, unless the stack is empty
508 public boolean popDirname() {
509 mDirectories
.remove(mDirectories
.getItem(0));
510 return !mDirectories
.isEmpty();
514 * Checks, whether or not there are any ownCloud accounts setup.
516 * @return true, if there is at least one account.
518 private boolean accountsAreSetup() {
519 AccountManager accMan
= AccountManager
.get(this);
520 Account
[] accounts
= accMan
521 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
);
522 return accounts
.length
> 0;
525 private class DirectoryCreator
implements Runnable
{
526 private String mTargetPath
;
527 private Account mAccount
;
528 private AccountManager mAm
;
530 public DirectoryCreator(String targetPath
, Account account
) {
531 mTargetPath
= targetPath
;
533 mAm
= (AccountManager
) getSystemService(ACCOUNT_SERVICE
);
538 WebdavClient wdc
= new WebdavClient(Uri
.parse(mAm
.getUserData(
539 mAccount
, AccountAuthenticator
.KEY_OC_URL
)));
541 String username
= mAccount
.name
.substring(0,
542 mAccount
.name
.lastIndexOf('@'));
543 String password
= mAm
.getPassword(mAccount
);
545 wdc
.setCredentials(username
, password
);
546 wdc
.allowSelfsignedCertificates();
547 wdc
.createDirectory(mTargetPath
);
552 // Custom array adapter to override text colors
553 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
555 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
559 public View
getView(int position
, View convertView
, ViewGroup parent
) {
560 View v
= super.getView(position
, convertView
, parent
);
562 ((TextView
) v
).setTextColor(getResources().getColorStateList(
563 android
.R
.color
.white
));
567 public View
getDropDownView(int position
, View convertView
,
569 View v
= super.getDropDownView(position
, convertView
, parent
);
571 ((TextView
) v
).setTextColor(getResources().getColorStateList(
572 android
.R
.color
.white
));
579 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
581 * {@link BroadcastReceiver} to enable syncing feedback in UI
584 public void onReceive(Context context
, Intent intent
) {
585 boolean inProgress
= intent
.getBooleanExtra(
586 FileSyncService
.IN_PROGRESS
, false
);
587 String account_name
= intent
588 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
589 Log
.d("FileDisplay", "sync of account " + account_name
590 + " is in_progress: " + inProgress
);
591 setProgressBarIndeterminateVisibility(inProgress
);
593 FileListFragment fileListFramgent
= (FileListFragment
) getSupportFragmentManager()
594 .findFragmentById(R
.id
.fileList
);
595 if (fileListFramgent
!= null
)
596 fileListFramgent
.listDirectory();
603 public void onClick(View v
) {
604 if (v
.getId() == R
.id
.setup_account
) {
605 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
606 intent
.putExtra("authorities", new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
607 startActivity(intent
);
611 public DataStorageManager
getStorageManager() {
612 return mStorageManager
;