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
;
48 import android
.widget
.Toast
;
50 import com
.actionbarsherlock
.app
.ActionBar
;
51 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
52 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
53 import com
.actionbarsherlock
.view
.Menu
;
54 import com
.actionbarsherlock
.view
.MenuInflater
;
55 import com
.actionbarsherlock
.view
.MenuItem
;
56 import com
.actionbarsherlock
.view
.Window
;
58 import eu
.alefzero
.owncloud
.AccountUtils
;
59 import eu
.alefzero
.owncloud
.CrashHandler
;
60 import eu
.alefzero
.owncloud
.R
;
61 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
62 import eu
.alefzero
.owncloud
.datamodel
.DataStorageManager
;
63 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
64 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
65 import eu
.alefzero
.owncloud
.files
.services
.FileDownloader
;
66 import eu
.alefzero
.owncloud
.files
.services
.FileUploader
;
67 import eu
.alefzero
.owncloud
.syncadapter
.FileSyncService
;
68 import eu
.alefzero
.owncloud
.ui
.fragment
.FileDetailFragment
;
69 import eu
.alefzero
.owncloud
.ui
.fragment
.FileListFragment
;
70 import eu
.alefzero
.webdav
.WebdavClient
;
73 * Displays, what files the user has available in his ownCloud.
75 * @author Bartek Przybylski
79 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
80 OnNavigationListener
, OnClickListener
, android
.view
.View
.OnClickListener
{
82 private ArrayAdapter
<String
> mDirectories
;
83 private OCFile mCurrentDir
;
84 private String
[] mDirs
= null
;
86 private DataStorageManager mStorageManager
;
87 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
88 private UploadFinishReceiver mUploadFinishReceiver
;
90 private View mLayoutView
= null
;
91 private FileListFragment mFileList
;
93 private static final String KEY_DIR_ARRAY
= "DIR_ARRAY";
94 private static final String KEY_CURRENT_DIR
= "DIR";
96 private static final int DIALOG_SETUP_ACCOUNT
= 0;
97 private static final int DIALOG_CREATE_DIR
= 1;
98 private static final int DIALOG_ABOUT_APP
= 2;
100 private static final int ACTION_SELECT_FILE
= 1;
101 //private static final int ACTION_CREATE_FIRST_ACCOUNT = 2; dvelasco: WIP
104 public void onCreate(Bundle savedInstanceState
) {
105 Log
.i(getClass().toString(), "onCreate() start");
106 super.onCreate(savedInstanceState
);
108 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
109 setSupportProgressBarIndeterminateVisibility(false
);
111 Thread
.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
113 if(savedInstanceState
!= null
){
114 mCurrentDir
= (OCFile
) savedInstanceState
.getParcelable(KEY_CURRENT_DIR
); // this is never saved with this key :S
117 mLayoutView
= getLayoutInflater().inflate(R
.layout
.files
, null
); // always inflate this at onCreate() ; just once!
119 if (AccountUtils
.accountsAreSetup(this)) {
120 setContentView(mLayoutView
);
123 setContentView(R
.layout
.no_account_available
);
124 setProgressBarIndeterminateVisibility(false
);
125 getSupportActionBar().setNavigationMode(ActionBar
.DISPLAY_SHOW_TITLE
);
126 findViewById(R
.id
.setup_account
).setOnClickListener(this);
129 Log
.i(getClass().toString(), "onCreate() end");
133 public boolean onCreateOptionsMenu(Menu menu
) {
134 MenuInflater inflater
= getSherlock().getMenuInflater();
135 inflater
.inflate(R
.menu
.menu
, menu
);
140 public boolean onOptionsItemSelected(MenuItem item
) {
141 boolean retval
= true
;
142 switch (item
.getItemId()) {
143 case R
.id
.createDirectoryItem
: {
144 showDialog(DIALOG_CREATE_DIR
);
147 case R
.id
.startSync
: {
148 Bundle bundle
= new Bundle();
149 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
150 ContentResolver
.requestSync(
151 AccountUtils
.getCurrentOwnCloudAccount(this),
152 "org.owncloud", bundle
);
155 case R
.id
.action_upload
: {
156 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
157 action
= action
.setType("*/*")
158 .addCategory(Intent
.CATEGORY_OPENABLE
);
159 startActivityForResult(
160 Intent
.createChooser(action
, "Upload file from..."),
164 case R
.id
.action_settings
: {
165 Intent settingsIntent
= new Intent(this, Preferences
.class);
166 startActivity(settingsIntent
);
169 case R
.id
.about_app
: {
170 showDialog(DIALOG_ABOUT_APP
);
173 case android
.R
.id
.home
: {
174 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
186 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
187 int i
= itemPosition
;
195 * Called, when the user selected something for uploading
197 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
198 if (requestCode
== ACTION_SELECT_FILE
) {
199 if (resultCode
== RESULT_OK
) {
200 Uri selectedImageUri
= data
.getData();
202 String filemanagerstring
= selectedImageUri
.getPath();
203 String selectedImagePath
= getPath(selectedImageUri
);
206 if (selectedImagePath
!= null
)
207 filepath
= selectedImagePath
;
209 filepath
= filemanagerstring
;
211 if (filepath
== null
) {
212 Log
.e("FileDisplay", "Couldnt resolve path to file");
216 Intent i
= new Intent(this, FileUploader
.class);
217 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
218 AccountUtils
.getCurrentOwnCloudAccount(this));
219 String remotepath
= new String();
220 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
221 remotepath
+= "/" + mDirectories
.getItem(j
);
223 if (!remotepath
.endsWith("/"))
225 remotepath
+= new File(filepath
).getName();
226 remotepath
= Uri
.encode(remotepath
, "/");
228 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
229 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
230 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
234 }/* dvelasco: WIP - not working as expected ... yet :)
235 else if (requestCode == ACTION_CREATE_FIRST_ACCOUNT) {
236 if (resultCode != RESULT_OK) {
237 finish(); // the user cancelled the AuthenticatorActivity
243 public void onBackPressed() {
244 if (mDirectories
== null
|| mDirectories
.getCount() <= 1) {
249 mFileList
.onNavigateUp();
250 mCurrentDir
= mFileList
.getCurrentFile();
252 if(mCurrentDir
.getParentId() == 0){
253 ActionBar actionBar
= getSupportActionBar();
254 actionBar
.setDisplayHomeAsUpEnabled(false
);
259 protected void onRestoreInstanceState(Bundle savedInstanceState
) {
260 Log
.i(getClass().toString(), "onRestoreInstanceState() start");
261 super.onRestoreInstanceState(savedInstanceState
);
262 mDirs
= savedInstanceState
.getStringArray(KEY_DIR_ARRAY
);
263 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
264 mDirectories
.add("/");
266 for (String s
: mDirs
)
267 mDirectories
.insert(s
, 0);
268 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
269 Log
.i(getClass().toString(), "onRestoreInstanceState() end");
273 protected void onSaveInstanceState(Bundle outState
) {
274 Log
.i(getClass().toString(), "onSaveInstanceState() start");
275 super.onSaveInstanceState(outState
);
276 if(mDirectories
!= null
&& mDirectories
.getCount() != 0){
277 mDirs
= new String
[mDirectories
.getCount()-1];
278 for (int j
= mDirectories
.getCount() - 2, i
= 0; j
>= 0; --j
, ++i
) {
279 mDirs
[i
] = mDirectories
.getItem(j
);
282 outState
.putStringArray(KEY_DIR_ARRAY
, mDirs
);
283 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
284 Log
.i(getClass().toString(), "onSaveInstanceState() end");
288 protected void onResume() {
289 Log
.i(getClass().toString(), "onResume() start");
292 if (!AccountUtils
.accountsAreSetup(this)) {
293 /*Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
294 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
295 //startActivity(intent);
296 startActivityForResult(intent, ACTION_CREATE_FIRST_ACCOUNT);*/
298 } else { // at least an account exist: normal operation
300 // set the layout only if it couldn't be set in onCreate
301 if (findViewById(R
.id
.file_list_view
) == null
)
302 setContentView(mLayoutView
);
304 // Listen for sync messages
305 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
306 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
307 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
309 // Listen for upload messages
310 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
311 mUploadFinishReceiver
= new UploadFinishReceiver();
312 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
314 // Storage manager initialization
315 mStorageManager
= new FileDataStorageManager(
316 AccountUtils
.getCurrentOwnCloudAccount(this),
317 getContentResolver());
320 mFileList
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
322 // Figure out what directory to list.
323 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
324 if(getIntent().hasExtra(FileDetailFragment
.EXTRA_FILE
)){
325 mCurrentDir
= (OCFile
) getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
);
326 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()){
327 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
330 // Clear intent extra, so rotating the screen will not return us to this directory
331 getIntent().removeExtra(FileDetailFragment
.EXTRA_FILE
);
334 if (mCurrentDir
== null
)
335 mCurrentDir
= mStorageManager
.getFileByPath("/");
337 // Drop-Down navigation and file list restore
338 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
341 // Given the case we have a file to display:
342 if(mCurrentDir
!= null
){
343 ArrayList
<OCFile
> files
= new ArrayList
<OCFile
>();
344 OCFile currFile
= mCurrentDir
;
345 while(currFile
!= null
){
347 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
351 mDirs
= new String
[files
.size()];
352 for(int i
= files
.size() - 1; i
>= 0; i
--){
353 mDirs
[i
] = files
.get(i
).getFileName();
358 for (String s
: mDirs
)
361 mDirectories
.add("/");
365 ActionBar action_bar
= getSupportActionBar();
366 action_bar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
367 action_bar
.setDisplayShowTitleEnabled(false
);
368 action_bar
.setListNavigationCallbacks(mDirectories
, this);
369 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
370 action_bar
.setDisplayHomeAsUpEnabled(true
);
372 action_bar
.setDisplayHomeAsUpEnabled(false
);
376 mFileList
.listDirectory(mCurrentDir
);
378 Log
.i(getClass().toString(), "onResume() end");
382 protected void onPause() {
383 Log
.i(getClass().toString(), "onPause() start");
385 if (mSyncBroadcastReceiver
!= null
) {
386 unregisterReceiver(mSyncBroadcastReceiver
);
387 mSyncBroadcastReceiver
= null
;
389 if (mUploadFinishReceiver
!= null
) {
390 unregisterReceiver(mUploadFinishReceiver
);
391 mUploadFinishReceiver
= null
;
393 getIntent().putExtra(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
394 Log
.i(getClass().toString(), "onPause() end");
398 protected Dialog
onCreateDialog(int id
) {
399 Dialog dialog
= null
;
400 AlertDialog
.Builder builder
;
402 case DIALOG_SETUP_ACCOUNT
:
403 builder
= new AlertDialog
.Builder(this);
404 builder
.setTitle(R
.string
.main_tit_accsetup
);
405 builder
.setMessage(R
.string
.main_wrn_accsetup
);
406 builder
.setCancelable(false
);
407 builder
.setPositiveButton(android
.R
.string
.ok
, this);
408 builder
.setNegativeButton(android
.R
.string
.cancel
, this);
409 dialog
= builder
.create();
411 case DIALOG_ABOUT_APP
: {
412 builder
= new AlertDialog
.Builder(this);
413 builder
.setTitle("About");
416 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
417 builder
.setMessage("ownCloud android client\n\nversion: " + pkg
.versionName
);
418 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
419 dialog
= builder
.create();
420 } catch (NameNotFoundException e
) {
427 case DIALOG_CREATE_DIR
: {
428 builder
= new Builder(this);
429 final EditText dirNameInput
= new EditText(getBaseContext());
430 final Account a
= AccountUtils
.getCurrentOwnCloudAccount(this);
431 builder
.setView(dirNameInput
);
432 builder
.setTitle(R
.string
.uploader_info_dirname
);
433 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
434 dirNameInput
.setTextColor(typed_color
);
435 builder
.setPositiveButton(android
.R
.string
.ok
,
436 new OnClickListener() {
437 public void onClick(DialogInterface dialog
, int which
) {
438 String directoryName
= dirNameInput
.getText().toString();
439 if (directoryName
.trim().length() == 0) {
444 // Figure out the path where the dir needs to be created
446 if (mCurrentDir
== null
) {
447 // this is just a patch; we should ensure that mCurrentDir never is null
448 if (!mStorageManager
.fileExists("/")) {
449 OCFile file
= new OCFile("/");
450 mStorageManager
.saveFile(file
);
452 mCurrentDir
= mStorageManager
.getFileByPath("/");
454 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
457 path
+= Uri
.encode(directoryName
) + "/";
458 Thread thread
= new Thread(new DirectoryCreator(path
, a
));
461 // Save new directory in local database
462 OCFile newDir
= new OCFile(path
);
463 newDir
.setMimetype("DIR");
464 newDir
.setParentId(mCurrentDir
.getFileId());
465 mStorageManager
.saveFile(newDir
);
467 // Display the new folder right away
469 mFileList
.listDirectory(mCurrentDir
);
472 builder
.setNegativeButton(R
.string
.common_cancel
,
473 new OnClickListener() {
474 public void onClick(DialogInterface dialog
, int which
) {
478 dialog
= builder
.create();
490 * Responds to the "There are no ownCloud Accounts setup" dialog
491 * TODO: Dialog is 100% useless -> Remove
494 public void onClick(DialogInterface dialog
, int which
) {
495 // In any case - we won't need it anymore
498 case DialogInterface
.BUTTON_POSITIVE
:
499 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
500 intent
.putExtra("authorities",
501 new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
502 startActivity(intent
);
504 case DialogInterface
.BUTTON_NEGATIVE
:
511 * Translates a content URI of an image to a physical path
513 * @param uri The URI to resolve
514 * @return The path to the image or null if it could not be found
516 public String
getPath(Uri uri
) {
517 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
518 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
519 if (cursor
!= null
) {
520 int column_index
= cursor
521 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
522 cursor
.moveToFirst();
523 return cursor
.getString(column_index
);
529 * Pushes a directory to the drop down list
530 * @param directory to push
531 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
533 public void pushDirname(OCFile directory
) {
534 if(!directory
.isDirectory()){
535 throw new IllegalArgumentException("Only directories may be pushed!");
537 mDirectories
.insert(directory
.getFileName(), 0);
538 mCurrentDir
= directory
;
542 * Pops a directory name from the drop down list
543 * @return True, unless the stack is empty
545 public boolean popDirname() {
546 mDirectories
.remove(mDirectories
.getItem(0));
547 return !mDirectories
.isEmpty();
550 private class DirectoryCreator
implements Runnable
{
551 private String mTargetPath
;
552 private Account mAccount
;
553 private AccountManager mAm
;
555 public DirectoryCreator(String targetPath
, Account account
) {
556 mTargetPath
= targetPath
;
558 mAm
= (AccountManager
) getSystemService(ACCOUNT_SERVICE
);
563 WebdavClient wdc
= new WebdavClient(mAccount
, getApplicationContext());
565 String username
= mAccount
.name
.substring(0,
566 mAccount
.name
.lastIndexOf('@'));
567 String password
= mAm
.getPassword(mAccount
);
569 wdc
.setCredentials(username
, password
);
570 wdc
.allowSelfsignedCertificates();
571 wdc
.createDirectory(mTargetPath
);
576 // Custom array adapter to override text colors
577 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
579 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
583 public View
getView(int position
, View convertView
, ViewGroup parent
) {
584 View v
= super.getView(position
, convertView
, parent
);
586 ((TextView
) v
).setTextColor(getResources().getColorStateList(
587 android
.R
.color
.white
));
591 public View
getDropDownView(int position
, View convertView
,
593 View v
= super.getDropDownView(position
, convertView
, parent
);
595 ((TextView
) v
).setTextColor(getResources().getColorStateList(
596 android
.R
.color
.white
));
603 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
605 * {@link BroadcastReceiver} to enable syncing feedback in UI
608 public void onReceive(Context context
, Intent intent
) {
609 boolean inProgress
= intent
.getBooleanExtra(
610 FileSyncService
.IN_PROGRESS
, false
);
611 String account_name
= intent
612 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
613 Log
.d("FileDisplay", "sync of account " + account_name
614 + " is in_progress: " + inProgress
);
615 setSupportProgressBarIndeterminateVisibility(inProgress
);
617 long OCDirId
= intent
.getLongExtra(FileSyncService
.SYNC_FOLDER
, -1);
619 OCFile syncDir
= mStorageManager
.getFileById(OCDirId
);
620 if (syncDir
!= null
&& (
621 (mCurrentDir
== null
&& syncDir
.getFileName().equals("/")) ||
622 syncDir
.equals(mCurrentDir
))
624 FileListFragment fileListFragment
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
625 if (fileListFragment
!= null
) {
626 fileListFragment
.listDirectory();
632 FileListFragment fileListFragment
= (FileListFragment
) getSupportFragmentManager()
633 .findFragmentById(R
.id
.fileList
);
634 if (fileListFragment
!= null
)
635 fileListFragment
.listDirectory();
642 private class UploadFinishReceiver
extends BroadcastReceiver
{
644 * Once the file upload has finished -> update view
645 * @author David A. Velasco
646 * {@link BroadcastReceiver} to enable upload feedback in UI
649 public void onReceive(Context context
, Intent intent
) {
650 long parentDirId
= intent
.getLongExtra(FileUploader
.EXTRA_PARENT_DIR_ID
, -1);
651 OCFile parentDir
= mStorageManager
.getFileById(parentDirId
);
653 if (parentDir
!= null
&& (
654 (mCurrentDir
== null
&& parentDir
.getFileName().equals("/")) ||
655 parentDir
.equals(mCurrentDir
))
657 FileListFragment fileListFragment
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
658 if (fileListFragment
!= null
) {
659 fileListFragment
.listDirectory();
668 public void onClick(View v
) {
669 if (v
.getId() == R
.id
.setup_account
) {
670 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
671 intent
.putExtra("authorities", new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
672 startActivity(intent
);
676 public DataStorageManager
getStorageManager() {
677 return mStorageManager
;