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
.net
.URLEncoder
;
23 import java
.util
.ArrayList
;
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
;
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
;
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
;
69 * Displays, what files the user has available in his ownCloud.
71 * @author Bartek Przybylski
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
;
83 private SyncBroadcastReceiver syncBroadcastRevceiver
;
85 private static final String KEY_DIR_ARRAY
= "DIR_ARRAY";
86 private static final String KEY_CURRENT_DIR
= "DIR";
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;
93 public void onCreate(Bundle savedInstanceState
) {
94 super.onCreate(savedInstanceState
);
96 if (!accountsAreSetup()) {
97 showDialog(DIALOG_SETUP_ACCOUNT
);
101 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
102 setProgressBarIndeterminateVisibility(false
);
104 if(savedInstanceState
!= null
){
105 mCurrentDir
= (OCFile
) savedInstanceState
.getParcelable(KEY_CURRENT_DIR
);
108 setContentView(R
.layout
.files
);
112 public boolean onCreateOptionsMenu(Menu menu
) {
113 MenuInflater inflater
= getSherlock().getMenuInflater();
114 inflater
.inflate(R
.menu
.menu
, menu
);
119 public boolean onOptionsItemSelected(MenuItem item
) {
120 boolean retval
= true
;
121 switch (item
.getItemId()) {
122 case R
.id
.createDirectoryItem
: {
123 showDialog(DIALOG_CREATE_DIR
);
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
);
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..."),
143 case R
.id
.action_accounts
: {
144 Intent accountIntent
= new Intent(this, AccountSelectActivity
.class);
145 startActivity(accountIntent
);
147 case android
.R
.id
.home
: {
148 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
160 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
161 int i
= itemPosition
;
169 * Called, when the user selected something for uploading
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();
176 String filemanagerstring
= selectedImageUri
.getPath();
177 String selectedImagePath
= getPath(selectedImageUri
);
180 if (selectedImagePath
!= null
)
181 filepath
= selectedImagePath
;
183 filepath
= filemanagerstring
;
185 if (filepath
== null
) {
186 Log
.e("FileDisplay", "Couldnt resolve path to file");
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
));
197 if (!remotepath
.endsWith("/"))
199 remotepath
+= URLEncoder
.encode(new File(filepath
).getName());
200 Log
.e("ASD", remotepath
+ "");
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
);
211 public void onBackPressed() {
212 if (mDirectories
.getCount() == 1) {
217 mFileList
.onNavigateUp();
218 mCurrentDir
= mFileList
.getCurrentFile();
220 if(mCurrentDir
.getParentId() == 0){
221 ActionBar actionBar
= getSupportActionBar();
222 actionBar
.setDisplayHomeAsUpEnabled(false
);
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
);
233 mDirs
= savedInstanceState
.getStringArray(KEY_DIR_ARRAY
);
234 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
235 mDirectories
.add("/");
237 for (String s
: mDirs
)
238 mDirectories
.insert(s
, 0);
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
);
250 outState
.putStringArray(KEY_DIR_ARRAY
, mDirs
);
251 outState
.putParcelable(KEY_CURRENT_DIR
, mCurrentDir
);
255 protected void onResume() {
258 //TODO: Dialog useless -> get rid of this
259 if (!accountsAreSetup()) {
260 showDialog(DIALOG_SETUP_ACCOUNT
);
264 // Listen for sync messages
265 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
266 syncBroadcastRevceiver
= new SyncBroadcastReceiver();
267 registerReceiver(syncBroadcastRevceiver
, syncIntentFilter
);
269 // Storage manager initialization
270 mStorageManager
= new FileDataStorageManager(
271 AccountUtils
.getCurrentOwnCloudAccount(this),
272 getContentResolver());
275 mFileList
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
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());
285 // Clear intent extra, so rotating the screen will not return us to this directory
286 getIntent().removeExtra(FileDetailFragment
.EXTRA_FILE
);
289 // Drop-Down navigation and file list restore
290 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
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
){
299 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
303 mDirs
= new String
[files
.size()];
304 for(int i
= files
.size() - 1; i
>= 0; i
--){
305 mDirs
[i
] = files
.get(i
).getFileName();
310 for (String s
: mDirs
)
313 mDirectories
.add("/");
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
);
324 action_bar
.setDisplayHomeAsUpEnabled(false
);
329 mFileList
.listDirectory(mCurrentDir
);
333 protected void onPause() {
335 if (syncBroadcastRevceiver
!= null
) {
336 unregisterReceiver(syncBroadcastRevceiver
);
337 syncBroadcastRevceiver
= null
;
343 protected Dialog
onCreateDialog(int id
) {
345 AlertDialog
.Builder builder
;
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();
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
);
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) {
374 // Figure out the path where the dir needs to be created
375 String path
= mCurrentDir
.getRemotePath();
378 path
+= directoryName
+ "/";
379 Thread thread
= new Thread(new DirectoryCreator(
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
);
389 // Display the new folder right away
391 mFileList
.listDirectory(mCurrentDir
);
394 builder
.setNegativeButton(R
.string
.common_cancel
,
395 new OnClickListener() {
396 public void onClick(DialogInterface dialog
, int which
) {
400 dialog
= builder
.create();
412 * Responds to the "There are no ownCloud Accounts setup" dialog
413 * TODO: Dialog is 100% useless -> Remove
416 public void onClick(DialogInterface dialog
, int which
) {
417 // In any case - we won't need it anymore
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
);
426 case DialogInterface
.BUTTON_NEGATIVE
:
433 * Translates a content URI of an image to a physical path
435 * @param uri The URI to resolve
436 * @return The path to the image or null if it could not be found
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
);
451 * Pushes a directory to the drop down list
452 * @param directory to push
453 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
455 public void pushDirname(OCFile directory
) {
456 if(!directory
.isDirectory()){
457 throw new IllegalArgumentException("Only directories may be pushed!");
459 mDirectories
.insert(directory
.getFileName(), 0);
460 mCurrentDir
= directory
;
464 * Pops a directory name from the drop down list
465 * @return True, unless the stack is empty
467 public boolean popDirname() {
468 mDirectories
.remove(mDirectories
.getItem(0));
469 return !mDirectories
.isEmpty();
473 * Checks, whether or not there are any ownCloud accounts setup.
475 * @return true, if there is at least one account.
477 private boolean accountsAreSetup() {
478 AccountManager accMan
= AccountManager
.get(this);
479 Account
[] accounts
= accMan
480 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
);
481 return accounts
.length
> 0;
484 private class DirectoryCreator
implements Runnable
{
485 private String mTargetPath
;
486 private Account mAccount
;
487 private AccountManager mAm
;
489 public DirectoryCreator(String targetPath
, Account account
) {
490 mTargetPath
= targetPath
;
492 mAm
= (AccountManager
) getSystemService(ACCOUNT_SERVICE
);
497 WebdavClient wdc
= new WebdavClient(Uri
.parse(mAm
.getUserData(
498 mAccount
, AccountAuthenticator
.KEY_OC_URL
)));
500 String username
= mAccount
.name
.substring(0,
501 mAccount
.name
.lastIndexOf('@'));
502 String password
= mAm
.getPassword(mAccount
);
504 wdc
.setCredentials(username
, password
);
505 wdc
.allowUnsignedCertificates();
506 wdc
.createDirectory(mTargetPath
);
511 // Custom array adapter to override text colors
512 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
514 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
518 public View
getView(int position
, View convertView
, ViewGroup parent
) {
519 View v
= super.getView(position
, convertView
, parent
);
521 ((TextView
) v
).setTextColor(getResources().getColorStateList(
522 android
.R
.color
.white
));
526 public View
getDropDownView(int position
, View convertView
,
528 View v
= super.getDropDownView(position
, convertView
, parent
);
530 ((TextView
) v
).setTextColor(getResources().getColorStateList(
531 android
.R
.color
.white
));
538 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
540 * {@link BroadcastReceiver} to enable syncing feedback in UI
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
);
552 FileListFragment fileListFramgent
= (FileListFragment
) getSupportFragmentManager()
553 .findFragmentById(R
.id
.fileList
);
554 if (fileListFramgent
!= null
)
555 fileListFramgent
.listDirectory();