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
;
21 import java
.io
.BufferedReader
;
23 import java
.io
.InputStreamReader
;
24 import java
.lang
.Thread
.UncaughtExceptionHandler
;
25 import java
.net
.URLEncoder
;
26 import java
.util
.ArrayList
;
28 import android
.accounts
.Account
;
29 import android
.accounts
.AccountManager
;
30 import android
.app
.AlertDialog
;
31 import android
.app
.AlertDialog
.Builder
;
32 import android
.app
.Dialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ContentResolver
;
35 import android
.content
.Context
;
36 import android
.content
.DialogInterface
;
37 import android
.content
.DialogInterface
.OnClickListener
;
38 import android
.content
.Intent
;
39 import android
.content
.IntentFilter
;
40 import android
.database
.Cursor
;
41 import android
.net
.Uri
;
42 import android
.os
.Bundle
;
43 import android
.provider
.MediaStore
;
44 import android
.telephony
.TelephonyManager
;
45 import android
.util
.Log
;
46 import android
.view
.View
;
47 import android
.view
.ViewGroup
;
48 import android
.widget
.ArrayAdapter
;
49 import android
.widget
.CheckedTextView
;
50 import android
.widget
.EditText
;
51 import android
.widget
.TextView
;
53 import com
.actionbarsherlock
.app
.ActionBar
;
54 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
55 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
56 import com
.actionbarsherlock
.view
.Menu
;
57 import com
.actionbarsherlock
.view
.MenuInflater
;
58 import com
.actionbarsherlock
.view
.MenuItem
;
59 import com
.actionbarsherlock
.view
.Window
;
61 import eu
.alefzero
.owncloud
.AccountUtils
;
62 import eu
.alefzero
.owncloud
.CrashHandler
;
63 import eu
.alefzero
.owncloud
.R
;
64 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
65 import eu
.alefzero
.owncloud
.datamodel
.DataStorageManager
;
66 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
67 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
68 import eu
.alefzero
.owncloud
.files
.services
.FileUploader
;
69 import eu
.alefzero
.owncloud
.syncadapter
.FileSyncService
;
70 import eu
.alefzero
.owncloud
.ui
.fragment
.FileDetailFragment
;
71 import eu
.alefzero
.owncloud
.ui
.fragment
.FileListFragment
;
72 import eu
.alefzero
.webdav
.WebdavClient
;
75 * Displays, what files the user has available in his ownCloud.
77 * @author Bartek Przybylski
81 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
82 OnNavigationListener
, OnClickListener
, android
.view
.View
.OnClickListener
{
83 private ArrayAdapter
<String
> mDirectories
;
84 private DataStorageManager mStorageManager
;
85 private FileListFragment mFileList
;
86 private OCFile mCurrentDir
;
87 private String
[] mDirs
= null
;
89 private SyncBroadcastReceiver syncBroadcastRevceiver
;
91 private static final String KEY_DIR_ARRAY
= "DIR_ARRAY";
92 private static final String KEY_CURRENT_DIR
= "DIR";
94 private static final int DIALOG_SETUP_ACCOUNT
= 0;
95 private static final int DIALOG_CREATE_DIR
= 1;
96 private static final int ACTION_SELECT_FILE
= 1;
99 public void onCreate(Bundle savedInstanceState
) {
100 super.onCreate(savedInstanceState
);
102 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
103 setProgressBarIndeterminateVisibility(false
);
105 Thread
.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
107 if(savedInstanceState
!= null
){
108 mCurrentDir
= (OCFile
) savedInstanceState
.getParcelable(KEY_CURRENT_DIR
);
113 public boolean onCreateOptionsMenu(Menu menu
) {
114 MenuInflater inflater
= getSherlock().getMenuInflater();
115 inflater
.inflate(R
.menu
.menu
, menu
);
120 public boolean onOptionsItemSelected(MenuItem item
) {
121 boolean retval
= true
;
122 switch (item
.getItemId()) {
123 case R
.id
.createDirectoryItem
: {
124 showDialog(DIALOG_CREATE_DIR
);
127 case R
.id
.startSync
: {
128 Bundle bundle
= new Bundle();
129 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
130 ContentResolver
.requestSync(
131 AccountUtils
.getCurrentOwnCloudAccount(this),
132 "org.owncloud", bundle
);
135 case R
.id
.action_upload
: {
136 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
137 action
= action
.setType("*/*")
138 .addCategory(Intent
.CATEGORY_OPENABLE
);
139 startActivityForResult(
140 Intent
.createChooser(action
, "Upload file from..."),
144 case R
.id
.action_settings
: {
145 Intent settingsIntent
= new Intent(this, Preferences
.class);
146 startActivity(settingsIntent
);
148 case android
.R
.id
.home
: {
149 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
161 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
162 int i
= itemPosition
;
170 * Called, when the user selected something for uploading
172 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
173 if (resultCode
== RESULT_OK
) {
174 if (requestCode
== ACTION_SELECT_FILE
) {
175 Uri selectedImageUri
= data
.getData();
177 String filemanagerstring
= selectedImageUri
.getPath();
178 String selectedImagePath
= getPath(selectedImageUri
);
181 if (selectedImagePath
!= null
)
182 filepath
= selectedImagePath
;
184 filepath
= filemanagerstring
;
186 if (filepath
== null
) {
187 Log
.e("FileDisplay", "Couldnt resolve path to file");
191 Intent i
= new Intent(this, FileUploader
.class);
192 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
193 AccountUtils
.getCurrentOwnCloudAccount(this));
194 String remotepath
= new String();
195 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
196 remotepath
+= "/" + URLEncoder
.encode(mDirectories
.getItem(j
));
198 if (!remotepath
.endsWith("/"))
200 remotepath
+= URLEncoder
.encode(new File(filepath
).getName());
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
== null
|| 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 mDirs
= savedInstanceState
.getStringArray(KEY_DIR_ARRAY
);
230 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
231 mDirectories
.add("/");
233 for (String s
: mDirs
)
234 mDirectories
.insert(s
, 0);
238 protected void onSaveInstanceState(Bundle outState
) {
239 super.onSaveInstanceState(outState
);
240 if(mDirectories
!= null
&& mDirectories
.getCount() != 0){
241 mDirs
= new String
[mDirectories
.getCount()-1];
242 for (int j
= mDirectories
.getCount() - 2, i
= 0; j
>= 0; --j
, ++i
) {
243 mDirs
[i
] = mDirectories
.getItem(j
);
246 outState
.putStringArray(KEY_DIR_ARRAY
, mDirs
);
247 outState
.putParcelable(KEY_CURRENT_DIR
, mCurrentDir
);
251 protected void onResume() {
254 //TODO: Dialog useless -> get rid of this
255 if (!accountsAreSetup()) {
256 setContentView(R
.layout
.no_account_available
);
257 setProgressBarIndeterminateVisibility(false
);
258 getSupportActionBar().setNavigationMode(ActionBar
.DISPLAY_SHOW_TITLE
);
259 findViewById(R
.id
.setup_account
).setOnClickListener(this);
261 } else if (findViewById(R
.id
.file_list_view
) == null
) {
262 setContentView(R
.layout
.files
);
265 // Listen for sync messages
266 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
267 syncBroadcastRevceiver
= new SyncBroadcastReceiver();
268 registerReceiver(syncBroadcastRevceiver
, syncIntentFilter
);
270 // Storage manager initialization
271 mStorageManager
= new FileDataStorageManager(
272 AccountUtils
.getCurrentOwnCloudAccount(this),
273 getContentResolver());
276 mFileList
= (FileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
278 // Figure out what directory to list.
279 // Priority: Intent (here), savedInstanceState (onCreate), root dir (dir is null)
280 if(getIntent().hasExtra(FileDetailFragment
.EXTRA_FILE
)){
281 mCurrentDir
= (OCFile
) getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
);
282 if(!mCurrentDir
.isDirectory()){
283 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
286 // Clear intent extra, so rotating the screen will not return us to this directory
287 getIntent().removeExtra(FileDetailFragment
.EXTRA_FILE
);
290 // Drop-Down navigation and file list restore
291 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
294 // Given the case we have a file to display:
295 if(mCurrentDir
!= null
){
296 ArrayList
<OCFile
> files
= new ArrayList
<OCFile
>();
297 OCFile currFile
= mCurrentDir
;
298 while(currFile
!= null
){
300 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
304 mDirs
= new String
[files
.size()];
305 for(int i
= files
.size() - 1; i
>= 0; i
--){
306 mDirs
[i
] = files
.get(i
).getFileName();
311 for (String s
: mDirs
)
314 mDirectories
.add("/");
318 ActionBar action_bar
= getSupportActionBar();
319 action_bar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
320 action_bar
.setDisplayShowTitleEnabled(false
);
321 action_bar
.setListNavigationCallbacks(mDirectories
, this);
322 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
323 action_bar
.setDisplayHomeAsUpEnabled(true
);
325 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
.allowSelfsignedCertificates();
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();
562 public void onClick(View v
) {
563 if (v
.getId() == R
.id
.setup_account
) {
564 Intent intent
= new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
565 intent
.putExtra("authorities", new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
566 startActivity(intent
);