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
.URLDecoder
;
23 import java
.net
.URLEncoder
;
24 import java
.util
.ArrayList
;
25 import java
.util
.Arrays
;
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
.database
.Cursor
;
40 import android
.net
.Uri
;
41 import android
.os
.Bundle
;
42 import android
.provider
.MediaStore
;
43 import android
.util
.Log
;
44 import android
.view
.View
;
45 import android
.view
.ViewGroup
;
46 import android
.widget
.ArrayAdapter
;
47 import android
.widget
.EditText
;
48 import android
.widget
.TextView
;
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
.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
{
79 private ArrayAdapter
<String
> mDirectories
;
80 private DataStorageManager mStorageManager
;
81 private FileListFragment mFileList
;
82 private OCFile mCurrentDir
;
83 private String
[] mDirs
= null
;
85 private SyncBroadcastReceiver syncBroadcastRevceiver
;
87 private static final String KEY_DIR_ARRAY
= "DIR_ARRAY";
88 private static final String KEY_CURRENT_DIR
= "DIR";
90 private static final int DIALOG_SETUP_ACCOUNT
= 0;
91 private static final int DIALOG_CREATE_DIR
= 1;
92 private static final int ACTION_SELECT_FILE
= 1;
95 public void onCreate(Bundle savedInstanceState
) {
96 super.onCreate(savedInstanceState
);
98 if (!accountsAreSetup()) {
99 showDialog(DIALOG_SETUP_ACCOUNT
);
103 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
104 setProgressBarIndeterminateVisibility(false
);
106 if(savedInstanceState
!= null
){
107 mCurrentDir
= (OCFile
) savedInstanceState
.getParcelable(KEY_CURRENT_DIR
);
110 setContentView(R
.layout
.files
);
114 public boolean onCreateOptionsMenu(Menu menu
) {
115 MenuInflater inflater
= getSherlock().getMenuInflater();
116 inflater
.inflate(R
.menu
.menu
, menu
);
121 public boolean onOptionsItemSelected(MenuItem item
) {
122 boolean retval
= true
;
123 switch (item
.getItemId()) {
124 case R
.id
.createDirectoryItem
: {
125 showDialog(DIALOG_CREATE_DIR
);
128 case R
.id
.startSync
: {
129 Bundle bundle
= new Bundle();
130 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
131 ContentResolver
.requestSync(
132 AccountUtils
.getCurrentOwnCloudAccount(this),
133 "org.owncloud", bundle
);
136 case R
.id
.action_upload
: {
137 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
138 action
= action
.setType("*/*")
139 .addCategory(Intent
.CATEGORY_OPENABLE
);
140 startActivityForResult(
141 Intent
.createChooser(action
, "Upload file from..."),
146 case android
.R
.id
.home
: {
147 Intent i
= new Intent(this, AccountSelectActivity
.class);
159 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
160 int i
= itemPosition
;
168 * Called, when the user selected something for uploading
170 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
171 if (resultCode
== RESULT_OK
) {
172 if (requestCode
== ACTION_SELECT_FILE
) {
173 Uri selectedImageUri
= data
.getData();
175 String filemanagerstring
= selectedImageUri
.getPath();
176 String selectedImagePath
= getPath(selectedImageUri
);
179 if (selectedImagePath
!= null
)
180 filepath
= selectedImagePath
;
182 filepath
= filemanagerstring
;
184 if (filepath
== null
) {
185 Log
.e("FileDisplay", "Couldnt resolve path to file");
189 Intent i
= new Intent(this, FileUploader
.class);
190 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
191 AccountUtils
.getCurrentOwnCloudAccount(this));
192 String remotepath
= new String();
193 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
194 remotepath
+= "/" + URLEncoder
.encode(mDirectories
.getItem(j
));
196 if (!remotepath
.endsWith("/"))
198 remotepath
+= URLEncoder
.encode(new File(filepath
).getName());
199 Log
.e("ASD", remotepath
+ "");
201 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
202 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
203 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
210 public void onBackPressed() {
211 if (mDirectories
.getCount() == 1) {
216 mFileList
.onNavigateUp();
217 mCurrentDir
= mFileList
.getCurrentFile();
221 protected void onRestoreInstanceState(Bundle savedInstanceState
) {
222 super.onRestoreInstanceState(savedInstanceState
);
223 // Check, if there are ownCloud accounts
224 if (!accountsAreSetup()) {
225 showDialog(DIALOG_SETUP_ACCOUNT
);
227 mDirs
= savedInstanceState
.getStringArray(KEY_DIR_ARRAY
);
228 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
229 mDirectories
.add("/");
231 for (String s
: mDirs
)
232 mDirectories
.insert(s
, 0);
236 protected void onSaveInstanceState(Bundle outState
) {
237 super.onSaveInstanceState(outState
);
238 if(mDirectories
!= null
){
239 mDirs
= new String
[mDirectories
.getCount()-1];
240 for (int j
= mDirectories
.getCount() - 2, i
= 0; j
>= 0; --j
, ++i
) {
241 mDirs
[i
] = mDirectories
.getItem(j
);
244 outState
.putStringArray(KEY_DIR_ARRAY
, mDirs
);
245 outState
.putParcelable(KEY_CURRENT_DIR
, mCurrentDir
);
249 protected void onResume() {
252 //TODO: Dialog useless -> get rid of this
253 if (!accountsAreSetup()) {
254 showDialog(DIALOG_SETUP_ACCOUNT
);
258 // Listen for sync messages
259 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
260 syncBroadcastRevceiver
= new SyncBroadcastReceiver();
261 registerReceiver(syncBroadcastRevceiver
, syncIntentFilter
);
263 // Storage manager initialization
264 mStorageManager
= new FileDataStorageManager(
265 AccountUtils
.getCurrentOwnCloudAccount(this),
266 getContentResolver());
269 mFileList
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
271 // Figure out what directory to list.
272 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
273 if(getIntent().hasExtra(FileDetailFragment
.EXTRA_FILE
)){
274 mCurrentDir
= (OCFile
) getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
);
275 if(!mCurrentDir
.isDirectory()){
276 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
279 // Clear intent extra, so rotating the screen will not return us to this directory
280 getIntent().removeExtra(FileDetailFragment
.EXTRA_FILE
);
283 // Drop-Down navigation and file list restore
284 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
287 // Given the case we have a file to display:
288 if(mCurrentDir
!= null
){
289 ArrayList
<OCFile
> files
= new ArrayList
<OCFile
>();
290 OCFile currFile
= mCurrentDir
;
291 while(currFile
!= null
){
293 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
297 mDirs
= new String
[files
.size()];
298 for(int i
= files
.size() - 1; i
>= 0; i
--){
299 mDirs
[i
] = files
.get(i
).getFileName();
304 for (String s
: mDirs
)
307 mDirectories
.add("/");
311 ActionBar action_bar
= getSupportActionBar();
312 action_bar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
313 action_bar
.setDisplayShowTitleEnabled(false
);
314 action_bar
.setListNavigationCallbacks(mDirectories
, this);
315 action_bar
.setDisplayHomeAsUpEnabled(true
);
318 mFileList
.listDirectory(mCurrentDir
);
322 protected void onPause() {
324 if (syncBroadcastRevceiver
!= null
) {
325 unregisterReceiver(syncBroadcastRevceiver
);
326 syncBroadcastRevceiver
= null
;
332 protected Dialog
onCreateDialog(int id
) {
334 AlertDialog
.Builder builder
;
336 case DIALOG_SETUP_ACCOUNT
:
337 builder
= new AlertDialog
.Builder(this);
338 builder
.setTitle(R
.string
.main_tit_accsetup
);
339 builder
.setMessage(R
.string
.main_wrn_accsetup
);
340 builder
.setCancelable(false
);
341 builder
.setPositiveButton(android
.R
.string
.ok
, this);
342 builder
.setNegativeButton(android
.R
.string
.cancel
, this);
343 dialog
= builder
.create();
345 case DIALOG_CREATE_DIR
: {
346 builder
= new Builder(this);
347 final EditText dirNameInput
= new EditText(getBaseContext());
348 final Account a
= AccountUtils
.getCurrentOwnCloudAccount(this);
349 builder
.setView(dirNameInput
);
350 builder
.setTitle(R
.string
.uploader_info_dirname
);
351 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
352 dirNameInput
.setTextColor(typed_color
);
354 builder
.setPositiveButton(android
.R
.string
.ok
,
355 new OnClickListener() {
356 public void onClick(DialogInterface dialog
, int which
) {
357 String directoryName
= dirNameInput
.getText().toString();
358 if (directoryName
.trim().length() == 0) {
363 // Figure out the path where the dir needs to be created
364 String path
= mCurrentDir
.getRemotePath();
367 path
+= directoryName
+ "/";
368 Thread thread
= new Thread(new DirectoryCreator(
372 // Save new directory in local database
373 OCFile newDir
= new OCFile(path
);
374 newDir
.setMimetype("DIR");
375 newDir
.setParentId(mCurrentDir
.getFileId());
376 mStorageManager
.saveFile(newDir
);
378 // Display the new folder right away
380 mFileList
.listDirectory(mCurrentDir
);
383 builder
.setNegativeButton(R
.string
.common_cancel
,
384 new OnClickListener() {
385 public void onClick(DialogInterface dialog
, int which
) {
389 dialog
= builder
.create();
401 * Responds to the "There are no ownCloud Accounts setup" dialog
402 * TODO: Dialog is 100% useless -> Remove
405 public void onClick(DialogInterface dialog
, int which
) {
406 // In any case - we won't need it anymore
409 case DialogInterface
.BUTTON_POSITIVE
:
410 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
411 intent
.putExtra("authorities",
412 new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
413 startActivity(intent
);
415 case DialogInterface
.BUTTON_NEGATIVE
:
422 * Translates a content URI of an image to a physical path
424 * @param uri The URI to resolve
425 * @return The path to the image or null if it could not be found
427 public String
getPath(Uri uri
) {
428 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
429 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
430 if (cursor
!= null
) {
431 int column_index
= cursor
432 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
433 cursor
.moveToFirst();
434 return cursor
.getString(column_index
);
440 * Pushes a directory to the drop down list
441 * @param directory to push
442 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
444 public void pushDirname(OCFile directory
) {
445 if(!directory
.isDirectory()){
446 throw new IllegalArgumentException("Only directories may be pushed!");
448 mDirectories
.insert(directory
.getFileName(), 0);
449 mCurrentDir
= directory
;
453 * Pops a directory name from the drop down list
454 * @return True, unless the stack is empty
456 public boolean popDirname() {
457 mDirectories
.remove(mDirectories
.getItem(0));
458 return !mDirectories
.isEmpty();
462 * Checks, whether or not there are any ownCloud accounts setup.
464 * @return true, if there is at least one account.
466 private boolean accountsAreSetup() {
467 AccountManager accMan
= AccountManager
.get(this);
468 Account
[] accounts
= accMan
469 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
);
470 return accounts
.length
> 0;
473 private class DirectoryCreator
implements Runnable
{
474 private String mTargetPath
;
475 private Account mAccount
;
476 private AccountManager mAm
;
478 public DirectoryCreator(String targetPath
, Account account
) {
479 mTargetPath
= targetPath
;
481 mAm
= (AccountManager
) getSystemService(ACCOUNT_SERVICE
);
486 WebdavClient wdc
= new WebdavClient(Uri
.parse(mAm
.getUserData(
487 mAccount
, AccountAuthenticator
.KEY_OC_URL
)));
489 String username
= mAccount
.name
.substring(0,
490 mAccount
.name
.lastIndexOf('@'));
491 String password
= mAm
.getPassword(mAccount
);
493 wdc
.setCredentials(username
, password
);
494 wdc
.allowUnsignedCertificates();
495 wdc
.createDirectory(mTargetPath
);
500 // Custom array adapter to override text colors
501 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
503 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
507 public View
getView(int position
, View convertView
, ViewGroup parent
) {
508 View v
= super.getView(position
, convertView
, parent
);
510 ((TextView
) v
).setTextColor(getResources().getColorStateList(
511 android
.R
.color
.white
));
515 public View
getDropDownView(int position
, View convertView
,
517 View v
= super.getDropDownView(position
, convertView
, parent
);
519 ((TextView
) v
).setTextColor(getResources().getColorStateList(
520 android
.R
.color
.white
));
527 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
529 * {@link BroadcastReceiver} to enable syncing feedback in UI
532 public void onReceive(Context context
, Intent intent
) {
533 boolean inProgress
= intent
.getBooleanExtra(
534 FileSyncService
.IN_PROGRESS
, false
);
535 String account_name
= intent
536 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
537 Log
.d("FileDisplay", "sync of account " + account_name
538 + " is in_progress: " + inProgress
);
539 setProgressBarIndeterminateVisibility(inProgress
);
541 FileListFragment fileListFramgent
= (FileListFragment
) getSupportFragmentManager()
542 .findFragmentById(R
.id
.fileList
);
543 if (fileListFramgent
!= null
)
544 fileListFramgent
.listDirectory();