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 com
.owncloud
.android
.ui
.activity
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.ProgressDialog
;
26 import android
.app
.AlertDialog
.Builder
;
27 import android
.app
.Dialog
;
28 import android
.content
.BroadcastReceiver
;
29 import android
.content
.ComponentName
;
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
.ServiceConnection
;
37 import android
.content
.SharedPreferences
;
38 import android
.content
.pm
.PackageInfo
;
39 import android
.content
.pm
.PackageManager
.NameNotFoundException
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Bundle
;
44 import android
.os
.Handler
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.FragmentTransaction
;
49 import android
.util
.Log
;
50 import android
.view
.View
;
51 import android
.view
.ViewGroup
;
52 import android
.widget
.ArrayAdapter
;
53 import android
.widget
.EditText
;
54 import android
.widget
.TextView
;
55 import android
.widget
.Toast
;
57 import com
.actionbarsherlock
.app
.ActionBar
;
58 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
59 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
60 import com
.actionbarsherlock
.view
.Menu
;
61 import com
.actionbarsherlock
.view
.MenuInflater
;
62 import com
.actionbarsherlock
.view
.MenuItem
;
63 import com
.actionbarsherlock
.view
.Window
;
64 import com
.owncloud
.android
.AccountUtils
;
65 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
66 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
67 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
68 import com
.owncloud
.android
.datamodel
.OCFile
;
69 import com
.owncloud
.android
.files
.services
.FileDownloader
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
73 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
74 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
75 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
76 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
77 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
78 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
79 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
81 import com
.owncloud
.android
.R
;
82 import eu
.alefzero
.webdav
.WebdavClient
;
85 * Displays, what files the user has available in his ownCloud.
87 * @author Bartek Przybylski
91 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
92 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
{
94 private ArrayAdapter
<String
> mDirectories
;
95 private OCFile mCurrentDir
= null
;
96 private OCFile mCurrentFile
= null
;
98 private DataStorageManager mStorageManager
;
99 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
100 private UploadFinishReceiver mUploadFinishReceiver
;
101 private DownloadFinishReceiver mDownloadFinishReceiver
;
102 private FileDownloaderBinder mDownloaderBinder
= null
;
103 private FileUploaderBinder mUploaderBinder
= null
;
104 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
105 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
107 private OCFileListFragment mFileList
;
109 private boolean mDualPane
;
111 private static final int DIALOG_SETUP_ACCOUNT
= 0;
112 private static final int DIALOG_CREATE_DIR
= 1;
113 private static final int DIALOG_ABOUT_APP
= 2;
114 public static final int DIALOG_SHORT_WAIT
= 3;
115 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
116 private static final int DIALOG_SSL_VALIDATOR
= 5;
117 private static final int DIALOG_CERT_NOT_SAVED
= 6;
120 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
121 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
123 private static final String TAG
= "FileDisplayActivity";
126 public void onCreate(Bundle savedInstanceState
) {
127 Log
.d(getClass().toString(), "onCreate() start");
128 super.onCreate(savedInstanceState
);
130 /// Load of parameters from received intent
131 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
132 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
134 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
136 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
137 if(savedInstanceState
!= null
) {
138 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
139 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
142 if (!AccountUtils
.accountsAreSetup(this)) {
143 /// no account available: FORCE ACCOUNT CREATION
144 mStorageManager
= null
;
145 createFirstAccount();
147 } else { /// at least an account is available
149 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
153 mUploadConnection
= new ListServiceConnection();
154 mDownloadConnection
= new ListServiceConnection();
155 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
156 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
158 // PIN CODE request ; best location is to decide, let's try this first
159 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
164 /*Intent observer_intent = new Intent(this, FileObserverService.class);
165 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
166 startService(observer_intent);
170 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
172 // Drop-down navigation
173 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
174 OCFile currFile
= mCurrentDir
;
175 while(currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
176 mDirectories
.add(currFile
.getFileName());
177 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
179 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
181 // Inflate and set the layout view
182 setContentView(R
.layout
.files
);
183 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
184 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
186 initFileDetailsInDualPane();
190 ActionBar actionBar
= getSupportActionBar();
191 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
192 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
193 actionBar
.setDisplayShowTitleEnabled(false
);
194 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
195 actionBar
.setListNavigationCallbacks(mDirectories
, this);
196 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
198 Log
.d(getClass().toString(), "onCreate() end");
203 * Launches the account creation activity. To use when no ownCloud account is available
205 private void createFirstAccount() {
206 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
207 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
208 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
213 * Load of state dependent of the existence of an ownCloud account
215 private void initDataFromCurrentAccount() {
216 /// Storage manager initialization - access to local database
217 mStorageManager
= new FileDataStorageManager(
218 AccountUtils
.getCurrentOwnCloudAccount(this),
219 getContentResolver());
221 /// Check if mCurrentDir is a directory
222 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
223 mCurrentFile
= mCurrentDir
;
224 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
227 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
228 if (mCurrentDir
!= null
) {
229 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
231 if (mCurrentFile
!= null
) {
232 if (mCurrentFile
.fileExists()) {
233 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
234 } // else : keep mCurrentFile with the received value; this is currently the case of an upload in progress, when the user presses the status notification in a landscape tablet
237 /// Default to root if mCurrentDir was not found
238 if (mCurrentDir
== null
) {
239 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
244 private void initFileDetailsInDualPane() {
245 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
246 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
247 if (mCurrentFile
!= null
) {
248 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
); // empty FileDetailFragment
251 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
253 transaction
.commit();
259 public void onDestroy() {
261 if (mDownloadConnection
!= null
)
262 unbindService(mDownloadConnection
);
263 if (mUploadConnection
!= null
)
264 unbindService(mUploadConnection
);
269 public boolean onCreateOptionsMenu(Menu menu
) {
270 MenuInflater inflater
= getSherlock().getMenuInflater();
271 inflater
.inflate(R
.menu
.menu
, menu
);
276 public boolean onOptionsItemSelected(MenuItem item
) {
277 boolean retval
= true
;
278 switch (item
.getItemId()) {
279 case R
.id
.createDirectoryItem
: {
280 showDialog(DIALOG_CREATE_DIR
);
283 case R
.id
.startSync
: {
284 startSynchronization();
287 case R
.id
.action_upload
: {
288 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
291 case R
.id
.action_settings
: {
292 Intent settingsIntent
= new Intent(this, Preferences
.class);
293 startActivity(settingsIntent
);
296 case R
.id
.about_app
: {
297 showDialog(DIALOG_ABOUT_APP
);
300 case android
.R
.id
.home
: {
301 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
312 private void startSynchronization() {
313 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
314 Bundle bundle
= new Bundle();
315 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
316 ContentResolver
.requestSync(
317 AccountUtils
.getCurrentOwnCloudAccount(this),
318 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
323 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
324 int i
= itemPosition
;
328 // the next operation triggers a new call to this method, but it's necessary to
329 // ensure that the name exposed in the action bar is the current directory when the
330 // user selected it in the navigation list
331 if (itemPosition
!= 0)
332 getSupportActionBar().setSelectedNavigationItem(0);
337 * Called, when the user selected something for uploading
339 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
341 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& resultCode
== RESULT_OK
) {
342 requestSimpleUpload(data
);
344 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& resultCode
== RESULT_OK
) {
345 requestMultipleUpload(data
);
350 private void requestMultipleUpload(Intent data
) {
351 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
352 if (filePaths
!= null
) {
353 String
[] remotePaths
= new String
[filePaths
.length
];
354 String remotePathBase
= "";
355 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
356 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
358 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
359 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
360 for (int j
= 0; j
< remotePaths
.length
; j
++) {
361 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
364 Intent i
= new Intent(this, FileUploader
.class);
365 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
366 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
367 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
368 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
372 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
373 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
380 private void requestSimpleUpload(Intent data
) {
381 String filepath
= null
;
383 Uri selectedImageUri
= data
.getData();
385 String filemanagerstring
= selectedImageUri
.getPath();
386 String selectedImagePath
= getPath(selectedImageUri
);
388 if (selectedImagePath
!= null
)
389 filepath
= selectedImagePath
;
391 filepath
= filemanagerstring
;
393 } catch (Exception e
) {
394 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
398 if (filepath
== null
) {
399 Log
.e("FileDisplay", "Couldnt resolve path to file");
400 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
406 Intent i
= new Intent(this, FileUploader
.class);
407 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
408 AccountUtils
.getCurrentOwnCloudAccount(this));
409 String remotepath
= new String();
410 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
411 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
413 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
414 remotepath
+= OCFile
.PATH_SEPARATOR
;
415 remotepath
+= new File(filepath
).getName();
417 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
418 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
419 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
425 public void onBackPressed() {
426 if (mDirectories
.getCount() <= 1) {
431 mFileList
.onNavigateUp();
432 mCurrentDir
= mFileList
.getCurrentFile();
435 // Resets the FileDetailsFragment on Tablets so that it always displays
436 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
437 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
438 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
439 transaction
.remove(fileDetails
);
440 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
441 transaction
.commit();
445 if(mCurrentDir
.getParentId() == 0){
446 ActionBar actionBar
= getSupportActionBar();
447 actionBar
.setDisplayHomeAsUpEnabled(false
);
452 protected void onSaveInstanceState(Bundle outState
) {
453 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
454 Log
.d(getClass().toString(), "onSaveInstanceState() start");
455 super.onSaveInstanceState(outState
);
456 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
458 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
459 if (fragment
!= null
) {
460 OCFile file
= fragment
.getDisplayedFile();
462 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
466 Log
.d(getClass().toString(), "onSaveInstanceState() end");
470 protected void onResume() {
471 Log
.d(getClass().toString(), "onResume() start");
474 if (AccountUtils
.accountsAreSetup(this)) {
476 if (mStorageManager
== null
) {
477 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
478 initDataFromCurrentAccount();
480 initFileDetailsInDualPane();
484 // Listen for sync messages
485 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
486 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
487 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
489 // Listen for upload messages
490 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
491 mUploadFinishReceiver
= new UploadFinishReceiver();
492 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
494 // Listen for download messages
495 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
496 mDownloadFinishReceiver
= new DownloadFinishReceiver();
497 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
499 // List current directory
500 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
504 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
505 showDialog(DIALOG_SETUP_ACCOUNT
);
508 Log
.d(getClass().toString(), "onResume() end");
513 protected void onPause() {
514 Log
.d(getClass().toString(), "onPause() start");
516 if (mSyncBroadcastReceiver
!= null
) {
517 unregisterReceiver(mSyncBroadcastReceiver
);
518 mSyncBroadcastReceiver
= null
;
520 if (mUploadFinishReceiver
!= null
) {
521 unregisterReceiver(mUploadFinishReceiver
);
522 mUploadFinishReceiver
= null
;
524 if (mDownloadFinishReceiver
!= null
) {
525 unregisterReceiver(mDownloadFinishReceiver
);
526 mDownloadFinishReceiver
= null
;
528 if (!AccountUtils
.accountsAreSetup(this)) {
529 dismissDialog(DIALOG_SETUP_ACCOUNT
);
532 Log
.d(getClass().toString(), "onPause() end");
537 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
538 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
539 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
545 protected Dialog
onCreateDialog(int id
) {
546 Dialog dialog
= null
;
547 AlertDialog
.Builder builder
;
549 case DIALOG_SETUP_ACCOUNT
: {
550 builder
= new AlertDialog
.Builder(this);
551 builder
.setTitle(R
.string
.main_tit_accsetup
);
552 builder
.setMessage(R
.string
.main_wrn_accsetup
);
553 builder
.setCancelable(false
);
554 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
555 public void onClick(DialogInterface dialog
, int which
) {
556 createFirstAccount();
560 builder
.setNegativeButton(R
.string
.common_exit
, new OnClickListener() {
561 public void onClick(DialogInterface dialog
, int which
) {
566 //builder.setNegativeButton(android.R.string.cancel, this);
567 dialog
= builder
.create();
570 case DIALOG_ABOUT_APP
: {
571 builder
= new AlertDialog
.Builder(this);
572 builder
.setTitle(getString(R
.string
.about_title
));
575 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
576 builder
.setMessage(String
.format(getString(R
.string
.about_message
), pkg
.versionName
));
577 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
578 dialog
= builder
.create();
579 } catch (NameNotFoundException e
) {
582 Log
.e(TAG
, "Error while showing about dialog", e
);
586 case DIALOG_CREATE_DIR
: {
587 builder
= new Builder(this);
588 final EditText dirNameInput
= new EditText(getBaseContext());
589 builder
.setView(dirNameInput
);
590 builder
.setTitle(R
.string
.uploader_info_dirname
);
591 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
592 dirNameInput
.setTextColor(typed_color
);
593 builder
.setPositiveButton(android
.R
.string
.ok
,
594 new OnClickListener() {
595 public void onClick(DialogInterface dialog
, int which
) {
596 String directoryName
= dirNameInput
.getText().toString();
597 if (directoryName
.trim().length() == 0) {
602 // Figure out the path where the dir needs to be created
604 if (mCurrentDir
== null
) {
605 // this is just a patch; we should ensure that mCurrentDir never is null
606 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
607 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
608 mStorageManager
.saveFile(file
);
610 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
612 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
615 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
616 Thread thread
= new Thread(new DirectoryCreator(path
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
621 showDialog(DIALOG_SHORT_WAIT
);
624 builder
.setNegativeButton(R
.string
.common_cancel
,
625 new OnClickListener() {
626 public void onClick(DialogInterface dialog
, int which
) {
630 dialog
= builder
.create();
633 case DIALOG_SHORT_WAIT
: {
634 ProgressDialog working_dialog
= new ProgressDialog(this);
635 working_dialog
.setMessage(getResources().getString(
636 R
.string
.wait_a_moment
));
637 working_dialog
.setIndeterminate(true
);
638 working_dialog
.setCancelable(false
);
639 dialog
= working_dialog
;
642 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
643 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
644 getString(R
.string
.actionbar_upload_from_apps
) };
645 builder
= new AlertDialog
.Builder(this);
646 builder
.setTitle(R
.string
.actionbar_upload
);
647 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
648 public void onClick(DialogInterface dialog
, int item
) {
651 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
652 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
654 // TODO create and handle new fragment LocalFileListFragment
656 } else if (item
== 1) {
657 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
658 action
= action
.setType("*/*")
659 .addCategory(Intent
.CATEGORY_OPENABLE
);
660 startActivityForResult(
661 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
662 ACTION_SELECT_CONTENT_FROM_APPS
);
666 dialog
= builder
.create();
669 case DIALOG_SSL_VALIDATOR
: {
670 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
673 case DIALOG_CERT_NOT_SAVED
: {
674 builder
= new AlertDialog
.Builder(this);
675 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
676 builder
.setCancelable(false
);
677 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
679 public void onClick(DialogInterface dialog
, int which
) {
683 dialog
= builder
.create();
695 * Translates a content URI of an image to a physical path
697 * @param uri The URI to resolve
698 * @return The path to the image or null if it could not be found
700 public String
getPath(Uri uri
) {
701 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
702 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
703 if (cursor
!= null
) {
704 int column_index
= cursor
705 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
706 cursor
.moveToFirst();
707 return cursor
.getString(column_index
);
713 * Pushes a directory to the drop down list
714 * @param directory to push
715 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
717 public void pushDirname(OCFile directory
) {
718 if(!directory
.isDirectory()){
719 throw new IllegalArgumentException("Only directories may be pushed!");
721 mDirectories
.insert(directory
.getFileName(), 0);
722 mCurrentDir
= directory
;
726 * Pops a directory name from the drop down list
727 * @return True, unless the stack is empty
729 public boolean popDirname() {
730 mDirectories
.remove(mDirectories
.getItem(0));
731 return !mDirectories
.isEmpty();
734 private class DirectoryCreator
implements Runnable
{
735 private String mTargetPath
;
736 private Account mAccount
;
737 private Handler mHandler
;
739 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
740 mTargetPath
= targetPath
;
747 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
748 boolean created
= wdc
.createDirectory(mTargetPath
);
750 mHandler
.post(new Runnable() {
753 dismissDialog(DIALOG_SHORT_WAIT
);
755 // Save new directory in local database
756 OCFile newDir
= new OCFile(mTargetPath
);
757 newDir
.setMimetype("DIR");
758 newDir
.setParentId(mCurrentDir
.getFileId());
759 mStorageManager
.saveFile(newDir
);
761 // Display the new folder right away
762 mFileList
.listDirectory();
767 mHandler
.post(new Runnable() {
770 dismissDialog(DIALOG_SHORT_WAIT
);
772 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
775 } catch (NotFoundException e
) {
776 Log
.e(TAG
, "Error while trying to show fail message " , e
);
785 // Custom array adapter to override text colors
786 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
788 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
792 public View
getView(int position
, View convertView
, ViewGroup parent
) {
793 View v
= super.getView(position
, convertView
, parent
);
795 ((TextView
) v
).setTextColor(getResources().getColorStateList(
796 android
.R
.color
.white
));
800 public View
getDropDownView(int position
, View convertView
,
802 View v
= super.getDropDownView(position
, convertView
, parent
);
804 ((TextView
) v
).setTextColor(getResources().getColorStateList(
805 android
.R
.color
.white
));
812 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
815 * {@link BroadcastReceiver} to enable syncing feedback in UI
818 public void onReceive(Context context
, Intent intent
) {
819 boolean inProgress
= intent
.getBooleanExtra(
820 FileSyncService
.IN_PROGRESS
, false
);
821 String accountName
= intent
822 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
824 Log
.d("FileDisplay", "sync of account " + accountName
825 + " is in_progress: " + inProgress
);
827 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
829 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
831 boolean fillBlankRoot
= false
;
832 if (mCurrentDir
== null
) {
833 mCurrentDir
= mStorageManager
.getFileByPath("/");
834 fillBlankRoot
= (mCurrentDir
!= null
);
837 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
840 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
841 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
842 .findFragmentById(R
.id
.fileList
);
843 if (fileListFragment
!= null
) {
844 fileListFragment
.listDirectory(mCurrentDir
);
848 setSupportProgressBarIndeterminateVisibility(inProgress
);
852 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncService
.SYNC_RESULT
);
853 if (synchResult
!= null
) {
854 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
855 mLastSslUntrustedServerResult
= synchResult
;
856 showDialog(DIALOG_SSL_VALIDATOR
);
863 private class UploadFinishReceiver
extends BroadcastReceiver
{
865 * Once the file upload has finished -> update view
866 * @author David A. Velasco
867 * {@link BroadcastReceiver} to enable upload feedback in UI
870 public void onReceive(Context context
, Intent intent
) {
871 long parentDirId
= intent
.getLongExtra(FileUploader
.EXTRA_PARENT_DIR_ID
, -1);
872 OCFile parentDir
= mStorageManager
.getFileById(parentDirId
);
873 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
875 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
) &&
877 ( (mCurrentDir
== null
&& parentDir
.getFileName().equals("/")) ||
878 parentDir
.equals(mCurrentDir
)
881 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
882 if (fileListFragment
!= null
) {
883 fileListFragment
.listDirectory();
892 * Once the file download has finished -> update view
894 private class DownloadFinishReceiver
extends BroadcastReceiver
{
896 public void onReceive(Context context
, Intent intent
) {
897 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
898 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
900 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
) &&
901 mCurrentDir
!= null
&& mCurrentDir
.getFileId() == mStorageManager
.getFileByPath(downloadedRemotePath
).getParentId()) {
902 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
903 if (fileListFragment
!= null
) {
904 fileListFragment
.listDirectory();
917 public DataStorageManager
getStorageManager() {
918 return mStorageManager
;
926 public void onDirectoryClick(OCFile directory
) {
927 pushDirname(directory
);
928 ActionBar actionBar
= getSupportActionBar();
929 actionBar
.setDisplayHomeAsUpEnabled(true
);
932 // Resets the FileDetailsFragment on Tablets so that it always displays
933 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
934 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
935 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
936 transaction
.remove(fileDetails
);
937 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
938 transaction
.commit();
948 public void onFileClick(OCFile file
) {
950 // If we are on a large device -> update fragment
952 // buttons in the details view are problematic when trying to reuse an existing fragment; create always a new one solves some of them, BUT no all; downloads are 'dangerous'
953 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
954 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
955 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
956 transaction
.commit();
958 } else { // small or medium screen device -> new Activity
959 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
960 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
961 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
962 startActivity(showDetailsIntent
);
971 public OCFile
getInitialDirectory() {
980 public void onFileStateChanged() {
981 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
982 if (fileListFragment
!= null
) {
983 fileListFragment
.listDirectory();
992 public FileDownloaderBinder
getFileDownloaderBinder() {
993 return mDownloaderBinder
;
1001 public FileUploaderBinder
getFileUploaderBinder() {
1002 return mUploaderBinder
;
1006 /** Defines callbacks for service binding, passed to bindService() */
1007 private class ListServiceConnection
implements ServiceConnection
{
1010 public void onServiceConnected(ComponentName component
, IBinder service
) {
1011 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1012 Log
.d(TAG
, "Download service connected");
1013 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1014 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1015 Log
.d(TAG
, "Upload service connected");
1016 mUploaderBinder
= (FileUploaderBinder
) service
;
1020 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1021 if (mFileList
!= null
)
1022 mFileList
.listDirectory();
1024 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1025 if (fragment
!= null
)
1026 fragment
.updateFileDetails();
1031 public void onServiceDisconnected(ComponentName component
) {
1032 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1033 Log
.d(TAG
, "Download service disconnected");
1034 mDownloaderBinder
= null
;
1035 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1036 Log
.d(TAG
, "Upload service disconnected");
1037 mUploaderBinder
= null
;
1045 * Launch an intent to request the PIN code to the user before letting him use the app
1047 private void requestPinCode() {
1048 boolean pinStart
= false
;
1049 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1050 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1052 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1053 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1060 public void onSavedCertificate() {
1061 startSynchronization();
1066 public void onFailedSavingCertificate() {
1067 showDialog(DIALOG_CERT_NOT_SAVED
);