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
.CheckedTextView
;
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
.R
;
59 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
60 import eu
.alefzero
.owncloud
.datamodel
.DataStorageManager
;
61 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
62 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
63 import eu
.alefzero
.owncloud
.files
.services
.FileUploader
;
64 import eu
.alefzero
.owncloud
.syncadapter
.FileSyncService
;
65 import eu
.alefzero
.owncloud
.ui
.fragment
.FileDetailFragment
;
66 import eu
.alefzero
.owncloud
.ui
.fragment
.FileListFragment
;
67 import eu
.alefzero
.webdav
.WebdavClient
;
70 * Displays, what files the user has available in his ownCloud.
72 * @author Bartek Przybylski
76 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
77 OnNavigationListener
, OnClickListener
, android
.view
.View
.OnClickListener
{
78 private ArrayAdapter
<String
> mDirectories
;
79 private DataStorageManager mStorageManager
;
80 private FileListFragment mFileList
;
81 private OCFile mCurrentDir
;
82 private String
[] mDirs
= null
;
84 private SyncBroadcastReceiver syncBroadcastRevceiver
;
86 private static final String KEY_DIR_ARRAY
= "DIR_ARRAY";
87 private static final String KEY_CURRENT_DIR
= "DIR";
89 private static final int DIALOG_SETUP_ACCOUNT
= 0;
90 private static final int DIALOG_CREATE_DIR
= 1;
91 private static final int ACTION_SELECT_FILE
= 1;
94 public void onCreate(Bundle savedInstanceState
) {
95 super.onCreate(savedInstanceState
);
97 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
98 setProgressBarIndeterminateVisibility(false
);
100 if(savedInstanceState
!= null
){
101 mCurrentDir
= (OCFile
) savedInstanceState
.getParcelable(KEY_CURRENT_DIR
);
106 public boolean onCreateOptionsMenu(Menu menu
) {
107 MenuInflater inflater
= getSherlock().getMenuInflater();
108 inflater
.inflate(R
.menu
.menu
, menu
);
113 public boolean onOptionsItemSelected(MenuItem item
) {
114 boolean retval
= true
;
115 switch (item
.getItemId()) {
116 case R
.id
.createDirectoryItem
: {
117 showDialog(DIALOG_CREATE_DIR
);
120 case R
.id
.startSync
: {
121 Bundle bundle
= new Bundle();
122 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
123 ContentResolver
.requestSync(
124 AccountUtils
.getCurrentOwnCloudAccount(this),
125 "org.owncloud", bundle
);
128 case R
.id
.action_upload
: {
129 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
130 action
= action
.setType("*/*")
131 .addCategory(Intent
.CATEGORY_OPENABLE
);
132 startActivityForResult(
133 Intent
.createChooser(action
, "Upload file from..."),
137 case R
.id
.action_accounts
: {
138 Intent accountIntent
= new Intent(this, AccountSelectActivity
.class);
139 startActivity(accountIntent
);
141 case android
.R
.id
.home
: {
142 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
154 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
155 int i
= itemPosition
;
163 * Called, when the user selected something for uploading
165 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
166 if (resultCode
== RESULT_OK
) {
167 if (requestCode
== ACTION_SELECT_FILE
) {
168 Uri selectedImageUri
= data
.getData();
170 String filemanagerstring
= selectedImageUri
.getPath();
171 String selectedImagePath
= getPath(selectedImageUri
);
174 if (selectedImagePath
!= null
)
175 filepath
= selectedImagePath
;
177 filepath
= filemanagerstring
;
179 if (filepath
== null
) {
180 Log
.e("FileDisplay", "Couldnt resolve path to file");
184 Intent i
= new Intent(this, FileUploader
.class);
185 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
186 AccountUtils
.getCurrentOwnCloudAccount(this));
187 String remotepath
= new String();
188 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
189 remotepath
+= "/" + URLEncoder
.encode(mDirectories
.getItem(j
));
191 if (!remotepath
.endsWith("/"))
193 remotepath
+= URLEncoder
.encode(new File(filepath
).getName());
194 Log
.e("ASD", remotepath
+ "");
196 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
197 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
198 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
205 public void onBackPressed() {
206 if (mDirectories
== null
|| mDirectories
.getCount() <= 1) {
211 mFileList
.onNavigateUp();
212 mCurrentDir
= mFileList
.getCurrentFile();
214 if(mCurrentDir
.getParentId() == 0){
215 ActionBar actionBar
= getSupportActionBar();
216 actionBar
.setDisplayHomeAsUpEnabled(false
);
221 protected void onRestoreInstanceState(Bundle savedInstanceState
) {
222 super.onRestoreInstanceState(savedInstanceState
);
223 mDirs
= savedInstanceState
.getStringArray(KEY_DIR_ARRAY
);
224 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
225 mDirectories
.add("/");
227 for (String s
: mDirs
)
228 mDirectories
.insert(s
, 0);
232 protected void onSaveInstanceState(Bundle outState
) {
233 super.onSaveInstanceState(outState
);
234 if(mDirectories
!= null
&& mDirectories
.getCount() != 0){
235 mDirs
= new String
[mDirectories
.getCount()-1];
236 for (int j
= mDirectories
.getCount() - 2, i
= 0; j
>= 0; --j
, ++i
) {
237 mDirs
[i
] = mDirectories
.getItem(j
);
240 outState
.putStringArray(KEY_DIR_ARRAY
, mDirs
);
241 outState
.putParcelable(KEY_CURRENT_DIR
, mCurrentDir
);
245 protected void onResume() {
248 //TODO: Dialog useless -> get rid of this
249 if (!accountsAreSetup()) {
250 setContentView(R
.layout
.no_account_available
);
251 setProgressBarIndeterminateVisibility(false
);
252 getSupportActionBar().setNavigationMode(ActionBar
.DISPLAY_SHOW_TITLE
);
253 findViewById(R
.id
.setup_account
).setOnClickListener(this);
255 } else if (findViewById(R
.id
.file_list_view
) == null
) {
256 setContentView(R
.layout
.files
);
259 // Listen for sync messages
260 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
261 syncBroadcastRevceiver
= new SyncBroadcastReceiver();
262 registerReceiver(syncBroadcastRevceiver
, syncIntentFilter
);
264 // Storage manager initialization
265 mStorageManager
= new FileDataStorageManager(
266 AccountUtils
.getCurrentOwnCloudAccount(this),
267 getContentResolver());
270 mFileList
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
272 // Figure out what directory to list.
273 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
274 if(getIntent().hasExtra(FileDetailFragment
.EXTRA_FILE
)){
275 mCurrentDir
= (OCFile
) getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
);
276 if(!mCurrentDir
.isDirectory()){
277 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
280 // Clear intent extra, so rotating the screen will not return us to this directory
281 getIntent().removeExtra(FileDetailFragment
.EXTRA_FILE
);
284 // Drop-Down navigation and file list restore
285 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
288 // Given the case we have a file to display:
289 if(mCurrentDir
!= null
){
290 ArrayList
<OCFile
> files
= new ArrayList
<OCFile
>();
291 OCFile currFile
= mCurrentDir
;
292 while(currFile
!= null
){
294 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
298 mDirs
= new String
[files
.size()];
299 for(int i
= files
.size() - 1; i
>= 0; i
--){
300 mDirs
[i
] = files
.get(i
).getFileName();
305 for (String s
: mDirs
)
308 mDirectories
.add("/");
312 ActionBar action_bar
= getSupportActionBar();
313 action_bar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
314 action_bar
.setDisplayShowTitleEnabled(false
);
315 action_bar
.setListNavigationCallbacks(mDirectories
, this);
316 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
317 action_bar
.setDisplayHomeAsUpEnabled(true
);
319 action_bar
.setDisplayHomeAsUpEnabled(false
);
323 mFileList
.listDirectory(mCurrentDir
);
327 protected void onPause() {
329 if (syncBroadcastRevceiver
!= null
) {
330 unregisterReceiver(syncBroadcastRevceiver
);
331 syncBroadcastRevceiver
= null
;
337 protected Dialog
onCreateDialog(int id
) {
339 AlertDialog
.Builder builder
;
341 case DIALOG_SETUP_ACCOUNT
:
342 builder
= new AlertDialog
.Builder(this);
343 builder
.setTitle(R
.string
.main_tit_accsetup
);
344 builder
.setMessage(R
.string
.main_wrn_accsetup
);
345 builder
.setCancelable(false
);
346 builder
.setPositiveButton(android
.R
.string
.ok
, this);
347 builder
.setNegativeButton(android
.R
.string
.cancel
, this);
348 dialog
= builder
.create();
350 case DIALOG_CREATE_DIR
: {
351 builder
= new Builder(this);
352 final EditText dirNameInput
= new EditText(getBaseContext());
353 final Account a
= AccountUtils
.getCurrentOwnCloudAccount(this);
354 builder
.setView(dirNameInput
);
355 builder
.setTitle(R
.string
.uploader_info_dirname
);
356 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
357 dirNameInput
.setTextColor(typed_color
);
359 builder
.setPositiveButton(android
.R
.string
.ok
,
360 new OnClickListener() {
361 public void onClick(DialogInterface dialog
, int which
) {
362 String directoryName
= dirNameInput
.getText().toString();
363 if (directoryName
.trim().length() == 0) {
368 // Figure out the path where the dir needs to be created
369 String path
= mCurrentDir
.getRemotePath();
372 path
+= directoryName
+ "/";
373 Thread thread
= new Thread(new DirectoryCreator(
377 // Save new directory in local database
378 OCFile newDir
= new OCFile(path
);
379 newDir
.setMimetype("DIR");
380 newDir
.setParentId(mCurrentDir
.getFileId());
381 mStorageManager
.saveFile(newDir
);
383 // Display the new folder right away
385 mFileList
.listDirectory(mCurrentDir
);
388 builder
.setNegativeButton(R
.string
.common_cancel
,
389 new OnClickListener() {
390 public void onClick(DialogInterface dialog
, int which
) {
394 dialog
= builder
.create();
406 * Responds to the "There are no ownCloud Accounts setup" dialog
407 * TODO: Dialog is 100% useless -> Remove
410 public void onClick(DialogInterface dialog
, int which
) {
411 // In any case - we won't need it anymore
414 case DialogInterface
.BUTTON_POSITIVE
:
415 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
416 intent
.putExtra("authorities",
417 new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
418 startActivity(intent
);
420 case DialogInterface
.BUTTON_NEGATIVE
:
427 * Translates a content URI of an image to a physical path
429 * @param uri The URI to resolve
430 * @return The path to the image or null if it could not be found
432 public String
getPath(Uri uri
) {
433 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
434 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
435 if (cursor
!= null
) {
436 int column_index
= cursor
437 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
438 cursor
.moveToFirst();
439 return cursor
.getString(column_index
);
445 * Pushes a directory to the drop down list
446 * @param directory to push
447 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
449 public void pushDirname(OCFile directory
) {
450 if(!directory
.isDirectory()){
451 throw new IllegalArgumentException("Only directories may be pushed!");
453 mDirectories
.insert(directory
.getFileName(), 0);
454 mCurrentDir
= directory
;
458 * Pops a directory name from the drop down list
459 * @return True, unless the stack is empty
461 public boolean popDirname() {
462 mDirectories
.remove(mDirectories
.getItem(0));
463 return !mDirectories
.isEmpty();
467 * Checks, whether or not there are any ownCloud accounts setup.
469 * @return true, if there is at least one account.
471 private boolean accountsAreSetup() {
472 AccountManager accMan
= AccountManager
.get(this);
473 Account
[] accounts
= accMan
474 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
);
475 return accounts
.length
> 0;
478 private class DirectoryCreator
implements Runnable
{
479 private String mTargetPath
;
480 private Account mAccount
;
481 private AccountManager mAm
;
483 public DirectoryCreator(String targetPath
, Account account
) {
484 mTargetPath
= targetPath
;
486 mAm
= (AccountManager
) getSystemService(ACCOUNT_SERVICE
);
491 WebdavClient wdc
= new WebdavClient(Uri
.parse(mAm
.getUserData(
492 mAccount
, AccountAuthenticator
.KEY_OC_URL
)));
494 String username
= mAccount
.name
.substring(0,
495 mAccount
.name
.lastIndexOf('@'));
496 String password
= mAm
.getPassword(mAccount
);
498 wdc
.setCredentials(username
, password
);
499 wdc
.allowSelfsignedCertificates();
500 wdc
.createDirectory(mTargetPath
);
505 // Custom array adapter to override text colors
506 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
508 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
512 public View
getView(int position
, View convertView
, ViewGroup parent
) {
513 View v
= super.getView(position
, convertView
, parent
);
515 ((TextView
) v
).setTextColor(getResources().getColorStateList(
516 android
.R
.color
.white
));
520 public View
getDropDownView(int position
, View convertView
,
522 View v
= super.getDropDownView(position
, convertView
, parent
);
524 ((TextView
) v
).setTextColor(getResources().getColorStateList(
525 android
.R
.color
.white
));
532 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
534 * {@link BroadcastReceiver} to enable syncing feedback in UI
537 public void onReceive(Context context
, Intent intent
) {
538 boolean inProgress
= intent
.getBooleanExtra(
539 FileSyncService
.IN_PROGRESS
, false
);
540 String account_name
= intent
541 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
542 Log
.d("FileDisplay", "sync of account " + account_name
543 + " is in_progress: " + inProgress
);
544 setProgressBarIndeterminateVisibility(inProgress
);
546 FileListFragment fileListFramgent
= (FileListFragment
) getSupportFragmentManager()
547 .findFragmentById(R
.id
.fileList
);
548 if (fileListFramgent
!= null
)
549 fileListFramgent
.listDirectory();
556 public void onClick(View v
) {
557 if (v
.getId() == R
.id
.setup_account
) {
558 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
559 intent
.putExtra("authorities", new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
560 startActivity(intent
);