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
;
22 import java
.util
.ArrayList
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.app
.AlertDialog
;
27 import android
.app
.AlertDialog
.Builder
;
28 import android
.app
.Dialog
;
29 import android
.content
.BroadcastReceiver
;
30 import android
.content
.ContentResolver
;
31 import android
.content
.Context
;
32 import android
.content
.DialogInterface
;
33 import android
.content
.DialogInterface
.OnClickListener
;
34 import android
.content
.Intent
;
35 import android
.content
.IntentFilter
;
36 import android
.content
.pm
.PackageInfo
;
37 import android
.content
.pm
.PackageManager
.NameNotFoundException
;
38 import android
.database
.Cursor
;
39 import android
.net
.Uri
;
40 import android
.os
.Bundle
;
41 import android
.provider
.MediaStore
;
42 import android
.util
.Log
;
43 import android
.view
.View
;
44 import android
.view
.ViewGroup
;
45 import android
.widget
.ArrayAdapter
;
46 import android
.widget
.EditText
;
47 import android
.widget
.TextView
;
49 import com
.actionbarsherlock
.app
.ActionBar
;
50 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
51 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
52 import com
.actionbarsherlock
.view
.Menu
;
53 import com
.actionbarsherlock
.view
.MenuInflater
;
54 import com
.actionbarsherlock
.view
.MenuItem
;
55 import com
.actionbarsherlock
.view
.Window
;
57 import eu
.alefzero
.owncloud
.AccountUtils
;
58 import eu
.alefzero
.owncloud
.CrashHandler
;
59 import eu
.alefzero
.owncloud
.R
;
60 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
61 import eu
.alefzero
.owncloud
.datamodel
.DataStorageManager
;
62 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
63 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
64 import eu
.alefzero
.owncloud
.files
.services
.FileUploader
;
65 import eu
.alefzero
.owncloud
.syncadapter
.FileSyncService
;
66 import eu
.alefzero
.owncloud
.ui
.fragment
.FileDetailFragment
;
67 import eu
.alefzero
.owncloud
.ui
.fragment
.FileListFragment
;
68 import eu
.alefzero
.webdav
.WebdavClient
;
71 * Displays, what files the user has available in his ownCloud.
73 * @author Bartek Przybylski
77 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
78 OnNavigationListener
, OnClickListener
, android
.view
.View
.OnClickListener
{
80 private ArrayAdapter
<String
> mDirectories
;
81 private OCFile mCurrentDir
;
82 private String
[] mDirs
= null
;
84 private DataStorageManager mStorageManager
;
85 private SyncBroadcastReceiver syncBroadcastReceiver
;
87 private View mLayoutView
= null
;
88 private FileListFragment mFileList
;
90 private static final String KEY_DIR_ARRAY
= "DIR_ARRAY";
91 private static final String KEY_CURRENT_DIR
= "DIR";
93 private static final int DIALOG_SETUP_ACCOUNT
= 0;
94 private static final int DIALOG_CREATE_DIR
= 1;
95 private static final int DIALOG_ABOUT_APP
= 2;
97 private static final int ACTION_SELECT_FILE
= 1;
98 //private static final int ACTION_CREATE_FIRST_ACCOUNT = 2; dvelasco: WIP
101 public void onCreate(Bundle savedInstanceState
) {
102 Log
.i(getClass().toString(), "onCreate() start");
103 super.onCreate(savedInstanceState
);
105 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
106 setSupportProgressBarIndeterminateVisibility(false
);
108 Thread
.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
110 if(savedInstanceState
!= null
){
111 mCurrentDir
= (OCFile
) savedInstanceState
.getParcelable(KEY_CURRENT_DIR
); // this is never saved with this key :S
114 mLayoutView
= getLayoutInflater().inflate(R
.layout
.files
, null
); // always inflate this at onCreate() ; just once!
116 if (AccountUtils
.accountsAreSetup(this)) {
117 setContentView(mLayoutView
);
120 setContentView(R
.layout
.no_account_available
);
121 setProgressBarIndeterminateVisibility(false
);
122 getSupportActionBar().setNavigationMode(ActionBar
.DISPLAY_SHOW_TITLE
);
123 findViewById(R
.id
.setup_account
).setOnClickListener(this);
126 Log
.i(getClass().toString(), "onCreate() end");
130 public boolean onCreateOptionsMenu(Menu menu
) {
131 MenuInflater inflater
= getSherlock().getMenuInflater();
132 inflater
.inflate(R
.menu
.menu
, menu
);
137 public boolean onOptionsItemSelected(MenuItem item
) {
138 boolean retval
= true
;
139 switch (item
.getItemId()) {
140 case R
.id
.createDirectoryItem
: {
141 showDialog(DIALOG_CREATE_DIR
);
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
);
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..."),
161 case R
.id
.action_settings
: {
162 Intent settingsIntent
= new Intent(this, Preferences
.class);
163 startActivity(settingsIntent
);
166 case R
.id
.about_app
: {
167 showDialog(DIALOG_ABOUT_APP
);
170 case android
.R
.id
.home
: {
171 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
183 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
184 int i
= itemPosition
;
192 * Called, when the user selected something for uploading
194 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
195 if (requestCode
== ACTION_SELECT_FILE
) {
196 if (resultCode
== RESULT_OK
) {
197 Uri selectedImageUri
= data
.getData();
199 String filemanagerstring
= selectedImageUri
.getPath();
200 String selectedImagePath
= getPath(selectedImageUri
);
203 if (selectedImagePath
!= null
)
204 filepath
= selectedImagePath
;
206 filepath
= filemanagerstring
;
208 if (filepath
== null
) {
209 Log
.e("FileDisplay", "Couldnt resolve path to file");
213 Intent i
= new Intent(this, FileUploader
.class);
214 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
215 AccountUtils
.getCurrentOwnCloudAccount(this));
216 String remotepath
= new String();
217 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
218 remotepath
+= "/" + mDirectories
.getItem(j
);
220 if (!remotepath
.endsWith("/"))
222 remotepath
+= new File(filepath
).getName();
223 remotepath
= Uri
.encode(remotepath
, "/");
225 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
226 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
227 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
231 }/* dvelasco: WIP - not working as expected ... yet :)
232 else if (requestCode == ACTION_CREATE_FIRST_ACCOUNT) {
233 if (resultCode != RESULT_OK) {
234 finish(); // the user cancelled the AuthenticatorActivity
240 public void onBackPressed() {
241 if (mDirectories
== null
|| mDirectories
.getCount() <= 1) {
246 mFileList
.onNavigateUp();
247 mCurrentDir
= mFileList
.getCurrentFile();
249 if(mCurrentDir
.getParentId() == 0){
250 ActionBar actionBar
= getSupportActionBar();
251 actionBar
.setDisplayHomeAsUpEnabled(false
);
256 protected void onRestoreInstanceState(Bundle savedInstanceState
) {
257 Log
.i(getClass().toString(), "onRestoreInstanceState() start");
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
);
266 Log
.i(getClass().toString(), "onRestoreInstanceState() end");
270 protected void onSaveInstanceState(Bundle outState
) {
271 Log
.i(getClass().toString(), "onSaveInstanceState() start");
272 super.onSaveInstanceState(outState
);
273 if(mDirectories
!= null
&& mDirectories
.getCount() != 0){
274 mDirs
= new String
[mDirectories
.getCount()-1];
275 for (int j
= mDirectories
.getCount() - 2, i
= 0; j
>= 0; --j
, ++i
) {
276 mDirs
[i
] = mDirectories
.getItem(j
);
279 outState
.putStringArray(KEY_DIR_ARRAY
, mDirs
);
280 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
281 Log
.i(getClass().toString(), "onSaveInstanceState() end");
285 protected void onResume() {
286 Log
.i(getClass().toString(), "onResume() start");
289 if (!AccountUtils
.accountsAreSetup(this)) {
290 /*Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
291 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
292 //startActivity(intent);
293 startActivityForResult(intent, ACTION_CREATE_FIRST_ACCOUNT);*/
295 } else { // at least an account exist: normal operation
297 // set the layout only if it couldn't be set in onCreate
298 if (findViewById(R
.id
.file_list_view
) == null
)
299 setContentView(mLayoutView
);
301 // Listen for sync messages
302 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
303 syncBroadcastReceiver
= new SyncBroadcastReceiver();
304 registerReceiver(syncBroadcastReceiver
, syncIntentFilter
);
306 // Storage manager initialization
307 mStorageManager
= new FileDataStorageManager(
308 AccountUtils
.getCurrentOwnCloudAccount(this),
309 getContentResolver());
312 mFileList
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
314 // Figure out what directory to list.
315 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
316 if(getIntent().hasExtra(FileDetailFragment
.EXTRA_FILE
)){
317 mCurrentDir
= (OCFile
) getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
);
318 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()){
319 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
322 // Clear intent extra, so rotating the screen will not return us to this directory
323 getIntent().removeExtra(FileDetailFragment
.EXTRA_FILE
);
326 if (mCurrentDir
== null
)
327 mCurrentDir
= mStorageManager
.getFileByPath("/");
329 // Drop-Down navigation and file list restore
330 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
333 // Given the case we have a file to display:
334 if(mCurrentDir
!= null
){
335 ArrayList
<OCFile
> files
= new ArrayList
<OCFile
>();
336 OCFile currFile
= mCurrentDir
;
337 while(currFile
!= null
){
339 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
343 mDirs
= new String
[files
.size()];
344 for(int i
= files
.size() - 1; i
>= 0; i
--){
345 mDirs
[i
] = files
.get(i
).getFileName();
350 for (String s
: mDirs
)
353 mDirectories
.add("/");
357 ActionBar action_bar
= getSupportActionBar();
358 action_bar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
359 action_bar
.setDisplayShowTitleEnabled(false
);
360 action_bar
.setListNavigationCallbacks(mDirectories
, this);
361 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
362 action_bar
.setDisplayHomeAsUpEnabled(true
);
364 action_bar
.setDisplayHomeAsUpEnabled(false
);
368 mFileList
.listDirectory(mCurrentDir
);
370 Log
.i(getClass().toString(), "onResume() end");
374 protected void onPause() {
375 Log
.i(getClass().toString(), "onPause() start");
377 if (syncBroadcastReceiver
!= null
) {
378 unregisterReceiver(syncBroadcastReceiver
);
379 syncBroadcastReceiver
= null
;
381 getIntent().putExtra(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
382 Log
.i(getClass().toString(), "onPause() end");
386 protected Dialog
onCreateDialog(int id
) {
387 Dialog dialog
= null
;
388 AlertDialog
.Builder builder
;
390 case DIALOG_SETUP_ACCOUNT
:
391 builder
= new AlertDialog
.Builder(this);
392 builder
.setTitle(R
.string
.main_tit_accsetup
);
393 builder
.setMessage(R
.string
.main_wrn_accsetup
);
394 builder
.setCancelable(false
);
395 builder
.setPositiveButton(android
.R
.string
.ok
, this);
396 builder
.setNegativeButton(android
.R
.string
.cancel
, this);
397 dialog
= builder
.create();
399 case DIALOG_ABOUT_APP
: {
400 builder
= new AlertDialog
.Builder(this);
401 builder
.setTitle("About");
404 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
405 builder
.setMessage("ownCloud android client\n\nversion: " + pkg
.versionName
);
406 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
407 dialog
= builder
.create();
408 } catch (NameNotFoundException e
) {
415 case DIALOG_CREATE_DIR
: {
416 builder
= new Builder(this);
417 final EditText dirNameInput
= new EditText(getBaseContext());
418 final Account a
= AccountUtils
.getCurrentOwnCloudAccount(this);
419 builder
.setView(dirNameInput
);
420 builder
.setTitle(R
.string
.uploader_info_dirname
);
421 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
422 dirNameInput
.setTextColor(typed_color
);
423 builder
.setPositiveButton(android
.R
.string
.ok
,
424 new OnClickListener() {
425 public void onClick(DialogInterface dialog
, int which
) {
426 String directoryName
= dirNameInput
.getText().toString();
427 if (directoryName
.trim().length() == 0) {
432 // Figure out the path where the dir needs to be created
434 if (mCurrentDir
== null
) {
435 // this is just a patch; we should ensure that mCurrentDir never is null
436 if (!mStorageManager
.fileExists("/")) {
437 OCFile file
= new OCFile("/");
438 mStorageManager
.saveFile(file
);
440 mCurrentDir
= mStorageManager
.getFileByPath("/");
442 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
445 path
+= Uri
.encode(directoryName
) + "/";
446 Thread thread
= new Thread(new DirectoryCreator(path
, a
));
449 // Save new directory in local database
450 OCFile newDir
= new OCFile(path
);
451 newDir
.setMimetype("DIR");
452 newDir
.setParentId(mCurrentDir
.getFileId());
453 mStorageManager
.saveFile(newDir
);
455 // Display the new folder right away
457 mFileList
.listDirectory(mCurrentDir
);
460 builder
.setNegativeButton(R
.string
.common_cancel
,
461 new OnClickListener() {
462 public void onClick(DialogInterface dialog
, int which
) {
466 dialog
= builder
.create();
478 * Responds to the "There are no ownCloud Accounts setup" dialog
479 * TODO: Dialog is 100% useless -> Remove
482 public void onClick(DialogInterface dialog
, int which
) {
483 // In any case - we won't need it anymore
486 case DialogInterface
.BUTTON_POSITIVE
:
487 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
488 intent
.putExtra("authorities",
489 new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
490 startActivity(intent
);
492 case DialogInterface
.BUTTON_NEGATIVE
:
499 * Translates a content URI of an image to a physical path
501 * @param uri The URI to resolve
502 * @return The path to the image or null if it could not be found
504 public String
getPath(Uri uri
) {
505 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
506 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
507 if (cursor
!= null
) {
508 int column_index
= cursor
509 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
510 cursor
.moveToFirst();
511 return cursor
.getString(column_index
);
517 * Pushes a directory to the drop down list
518 * @param directory to push
519 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
521 public void pushDirname(OCFile directory
) {
522 if(!directory
.isDirectory()){
523 throw new IllegalArgumentException("Only directories may be pushed!");
525 mDirectories
.insert(directory
.getFileName(), 0);
526 mCurrentDir
= directory
;
530 * Pops a directory name from the drop down list
531 * @return True, unless the stack is empty
533 public boolean popDirname() {
534 mDirectories
.remove(mDirectories
.getItem(0));
535 return !mDirectories
.isEmpty();
538 private class DirectoryCreator
implements Runnable
{
539 private String mTargetPath
;
540 private Account mAccount
;
541 private AccountManager mAm
;
543 public DirectoryCreator(String targetPath
, Account account
) {
544 mTargetPath
= targetPath
;
546 mAm
= (AccountManager
) getSystemService(ACCOUNT_SERVICE
);
551 WebdavClient wdc
= new WebdavClient(Uri
.parse(mAm
.getUserData(
552 mAccount
, AccountAuthenticator
.KEY_OC_URL
)));
554 String username
= mAccount
.name
.substring(0,
555 mAccount
.name
.lastIndexOf('@'));
556 String password
= mAm
.getPassword(mAccount
);
558 wdc
.setCredentials(username
, password
);
559 wdc
.allowSelfsignedCertificates();
560 wdc
.createDirectory(mTargetPath
);
565 // Custom array adapter to override text colors
566 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
568 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
572 public View
getView(int position
, View convertView
, ViewGroup parent
) {
573 View v
= super.getView(position
, convertView
, parent
);
575 ((TextView
) v
).setTextColor(getResources().getColorStateList(
576 android
.R
.color
.white
));
580 public View
getDropDownView(int position
, View convertView
,
582 View v
= super.getDropDownView(position
, convertView
, parent
);
584 ((TextView
) v
).setTextColor(getResources().getColorStateList(
585 android
.R
.color
.white
));
592 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
594 * {@link BroadcastReceiver} to enable syncing feedback in UI
597 public void onReceive(Context context
, Intent intent
) {
598 boolean inProgress
= intent
.getBooleanExtra(
599 FileSyncService
.IN_PROGRESS
, false
);
600 String account_name
= intent
601 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
602 Log
.d("FileDisplay", "sync of account " + account_name
603 + " is in_progress: " + inProgress
);
604 setSupportProgressBarIndeterminateVisibility(inProgress
);
606 FileListFragment fileListFragment
= (FileListFragment
) getSupportFragmentManager()
607 .findFragmentById(R
.id
.fileList
);
608 if (fileListFragment
!= null
)
609 fileListFragment
.listDirectory();
616 public void onClick(View v
) {
617 if (v
.getId() == R
.id
.setup_account
) {
618 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
619 intent
.putExtra("authorities", new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
620 startActivity(intent
);
624 public DataStorageManager
getStorageManager() {
625 return mStorageManager
;