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
.FileObserverService
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
74 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
75 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
76 import com
.owncloud
.android
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
79 import com
.owncloud
.android
.operations
.RenameFileOperation
;
80 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
81 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
82 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
83 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
85 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
86 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
88 import com
.owncloud
.android
.R
;
89 import eu
.alefzero
.webdav
.WebdavClient
;
92 * Displays, what files the user has available in his ownCloud.
94 * @author Bartek Przybylski
98 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
99 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, OnRemoteOperationListener
{
101 private ArrayAdapter
<String
> mDirectories
;
102 private OCFile mCurrentDir
= null
;
103 private OCFile mCurrentFile
= null
;
105 private DataStorageManager mStorageManager
;
106 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
107 private UploadFinishReceiver mUploadFinishReceiver
;
108 private DownloadFinishReceiver mDownloadFinishReceiver
;
109 private FileDownloaderBinder mDownloaderBinder
= null
;
110 private FileUploaderBinder mUploaderBinder
= null
;
111 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
112 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
114 private OCFileListFragment mFileList
;
116 private boolean mDualPane
;
118 private static final int DIALOG_SETUP_ACCOUNT
= 0;
119 private static final int DIALOG_CREATE_DIR
= 1;
120 private static final int DIALOG_ABOUT_APP
= 2;
121 public static final int DIALOG_SHORT_WAIT
= 3;
122 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
123 private static final int DIALOG_SSL_VALIDATOR
= 5;
124 private static final int DIALOG_CERT_NOT_SAVED
= 6;
127 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
128 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
130 private static final String TAG
= "FileDisplayActivity";
133 public void onCreate(Bundle savedInstanceState
) {
134 Log
.d(getClass().toString(), "onCreate() start");
135 super.onCreate(savedInstanceState
);
137 /// Load of parameters from received intent
138 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
139 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
141 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
143 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
144 if(savedInstanceState
!= null
) {
145 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
146 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
149 if (!AccountUtils
.accountsAreSetup(this)) {
150 /// no account available: FORCE ACCOUNT CREATION
151 mStorageManager
= null
;
152 createFirstAccount();
154 } else { /// at least an account is available
156 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
160 mUploadConnection
= new ListServiceConnection();
161 mDownloadConnection
= new ListServiceConnection();
162 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
163 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
165 // PIN CODE request ; best location is to decide, let's try this first
166 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
171 Intent observer_intent
= new Intent(this, FileObserverService
.class);
172 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
173 startService(observer_intent
);
177 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
179 // Drop-down navigation
180 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
181 OCFile currFile
= mCurrentDir
;
182 while(currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
183 mDirectories
.add(currFile
.getFileName());
184 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
186 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
188 // Inflate and set the layout view
189 setContentView(R
.layout
.files
);
190 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
191 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
193 initFileDetailsInDualPane();
197 ActionBar actionBar
= getSupportActionBar();
198 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
199 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
200 actionBar
.setDisplayShowTitleEnabled(false
);
201 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
202 actionBar
.setListNavigationCallbacks(mDirectories
, this);
203 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
205 Log
.d(getClass().toString(), "onCreate() end");
210 * Launches the account creation activity. To use when no ownCloud account is available
212 private void createFirstAccount() {
213 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
214 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
215 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
220 * Load of state dependent of the existence of an ownCloud account
222 private void initDataFromCurrentAccount() {
223 /// Storage manager initialization - access to local database
224 mStorageManager
= new FileDataStorageManager(
225 AccountUtils
.getCurrentOwnCloudAccount(this),
226 getContentResolver());
228 /// Check if mCurrentDir is a directory
229 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
230 mCurrentFile
= mCurrentDir
;
231 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
234 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
235 if (mCurrentDir
!= null
) {
236 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
238 if (mCurrentFile
!= null
) {
239 if (mCurrentFile
.fileExists()) {
240 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
241 } // 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
244 /// Default to root if mCurrentDir was not found
245 if (mCurrentDir
== null
) {
246 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
251 private void initFileDetailsInDualPane() {
252 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
253 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
254 if (mCurrentFile
!= null
) {
255 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
); // empty FileDetailFragment
258 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
260 transaction
.commit();
266 public void onDestroy() {
268 if (mDownloadConnection
!= null
)
269 unbindService(mDownloadConnection
);
270 if (mUploadConnection
!= null
)
271 unbindService(mUploadConnection
);
276 public boolean onCreateOptionsMenu(Menu menu
) {
277 MenuInflater inflater
= getSherlock().getMenuInflater();
278 inflater
.inflate(R
.menu
.menu
, menu
);
283 public boolean onOptionsItemSelected(MenuItem item
) {
284 boolean retval
= true
;
285 switch (item
.getItemId()) {
286 case R
.id
.createDirectoryItem
: {
287 showDialog(DIALOG_CREATE_DIR
);
290 case R
.id
.startSync
: {
291 startSynchronization();
294 case R
.id
.action_upload
: {
295 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
298 case R
.id
.action_settings
: {
299 Intent settingsIntent
= new Intent(this, Preferences
.class);
300 startActivity(settingsIntent
);
303 case R
.id
.about_app
: {
304 showDialog(DIALOG_ABOUT_APP
);
307 case android
.R
.id
.home
: {
308 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
314 retval
= super.onOptionsItemSelected(item
);
319 private void startSynchronization() {
320 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
321 Bundle bundle
= new Bundle();
322 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
323 ContentResolver
.requestSync(
324 AccountUtils
.getCurrentOwnCloudAccount(this),
325 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
330 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
331 int i
= itemPosition
;
335 // the next operation triggers a new call to this method, but it's necessary to
336 // ensure that the name exposed in the action bar is the current directory when the
337 // user selected it in the navigation list
338 if (itemPosition
!= 0)
339 getSupportActionBar().setSelectedNavigationItem(0);
344 * Called, when the user selected something for uploading
346 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
348 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& resultCode
== RESULT_OK
) {
349 requestSimpleUpload(data
);
351 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& resultCode
== RESULT_OK
) {
352 requestMultipleUpload(data
);
357 private void requestMultipleUpload(Intent data
) {
358 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
359 if (filePaths
!= null
) {
360 String
[] remotePaths
= new String
[filePaths
.length
];
361 String remotePathBase
= "";
362 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
363 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
365 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
366 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
367 for (int j
= 0; j
< remotePaths
.length
; j
++) {
368 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
371 Intent i
= new Intent(this, FileUploader
.class);
372 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
373 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
374 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
375 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
379 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
380 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
387 private void requestSimpleUpload(Intent data
) {
388 String filepath
= null
;
390 Uri selectedImageUri
= data
.getData();
392 String filemanagerstring
= selectedImageUri
.getPath();
393 String selectedImagePath
= getPath(selectedImageUri
);
395 if (selectedImagePath
!= null
)
396 filepath
= selectedImagePath
;
398 filepath
= filemanagerstring
;
400 } catch (Exception e
) {
401 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
405 if (filepath
== null
) {
406 Log
.e("FileDisplay", "Couldnt resolve path to file");
407 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
413 Intent i
= new Intent(this, FileUploader
.class);
414 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
415 AccountUtils
.getCurrentOwnCloudAccount(this));
416 String remotepath
= new String();
417 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
418 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
420 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
421 remotepath
+= OCFile
.PATH_SEPARATOR
;
422 remotepath
+= new File(filepath
).getName();
424 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
425 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
426 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
432 public void onBackPressed() {
433 if (mDirectories
.getCount() <= 1) {
438 mFileList
.onNavigateUp();
439 mCurrentDir
= mFileList
.getCurrentFile();
442 // Resets the FileDetailsFragment on Tablets so that it always displays
443 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
444 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
445 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
446 transaction
.remove(fileDetails
);
447 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
448 transaction
.commit();
452 if(mCurrentDir
.getParentId() == 0){
453 ActionBar actionBar
= getSupportActionBar();
454 actionBar
.setDisplayHomeAsUpEnabled(false
);
459 protected void onSaveInstanceState(Bundle outState
) {
460 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
461 Log
.d(getClass().toString(), "onSaveInstanceState() start");
462 super.onSaveInstanceState(outState
);
463 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
465 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
466 if (fragment
!= null
) {
467 OCFile file
= fragment
.getDisplayedFile();
469 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
473 Log
.d(getClass().toString(), "onSaveInstanceState() end");
477 protected void onResume() {
478 Log
.d(getClass().toString(), "onResume() start");
481 if (AccountUtils
.accountsAreSetup(this)) {
483 if (mStorageManager
== null
) {
484 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
485 initDataFromCurrentAccount();
487 initFileDetailsInDualPane();
491 // Listen for sync messages
492 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
493 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
494 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
496 // Listen for upload messages
497 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
498 mUploadFinishReceiver
= new UploadFinishReceiver();
499 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
501 // Listen for download messages
502 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
503 mDownloadFinishReceiver
= new DownloadFinishReceiver();
504 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
506 // List current directory
507 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
511 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
512 showDialog(DIALOG_SETUP_ACCOUNT
);
515 Log
.d(getClass().toString(), "onResume() end");
520 protected void onPause() {
521 Log
.d(getClass().toString(), "onPause() start");
523 if (mSyncBroadcastReceiver
!= null
) {
524 unregisterReceiver(mSyncBroadcastReceiver
);
525 mSyncBroadcastReceiver
= null
;
527 if (mUploadFinishReceiver
!= null
) {
528 unregisterReceiver(mUploadFinishReceiver
);
529 mUploadFinishReceiver
= null
;
531 if (mDownloadFinishReceiver
!= null
) {
532 unregisterReceiver(mDownloadFinishReceiver
);
533 mDownloadFinishReceiver
= null
;
535 if (!AccountUtils
.accountsAreSetup(this)) {
536 dismissDialog(DIALOG_SETUP_ACCOUNT
);
539 Log
.d(getClass().toString(), "onPause() end");
544 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
545 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
546 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
552 protected Dialog
onCreateDialog(int id
) {
553 Dialog dialog
= null
;
554 AlertDialog
.Builder builder
;
556 case DIALOG_SETUP_ACCOUNT
: {
557 builder
= new AlertDialog
.Builder(this);
558 builder
.setTitle(R
.string
.main_tit_accsetup
);
559 builder
.setMessage(R
.string
.main_wrn_accsetup
);
560 builder
.setCancelable(false
);
561 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
562 public void onClick(DialogInterface dialog
, int which
) {
563 createFirstAccount();
567 builder
.setNegativeButton(R
.string
.common_exit
, new OnClickListener() {
568 public void onClick(DialogInterface dialog
, int which
) {
573 //builder.setNegativeButton(android.R.string.cancel, this);
574 dialog
= builder
.create();
577 case DIALOG_ABOUT_APP
: {
578 builder
= new AlertDialog
.Builder(this);
579 builder
.setTitle(getString(R
.string
.about_title
));
582 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
583 builder
.setMessage(String
.format(getString(R
.string
.about_message
), pkg
.versionName
));
584 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
585 dialog
= builder
.create();
586 } catch (NameNotFoundException e
) {
589 Log
.e(TAG
, "Error while showing about dialog", e
);
593 case DIALOG_CREATE_DIR
: {
594 builder
= new Builder(this);
595 final EditText dirNameInput
= new EditText(getBaseContext());
596 builder
.setView(dirNameInput
);
597 builder
.setTitle(R
.string
.uploader_info_dirname
);
598 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
599 dirNameInput
.setTextColor(typed_color
);
600 builder
.setPositiveButton(android
.R
.string
.ok
,
601 new OnClickListener() {
602 public void onClick(DialogInterface dialog
, int which
) {
603 String directoryName
= dirNameInput
.getText().toString();
604 if (directoryName
.trim().length() == 0) {
609 // Figure out the path where the dir needs to be created
611 if (mCurrentDir
== null
) {
612 // this is just a patch; we should ensure that mCurrentDir never is null
613 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
614 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
615 mStorageManager
.saveFile(file
);
617 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
619 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
622 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
623 Thread thread
= new Thread(new DirectoryCreator(path
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
628 showDialog(DIALOG_SHORT_WAIT
);
631 builder
.setNegativeButton(R
.string
.common_cancel
,
632 new OnClickListener() {
633 public void onClick(DialogInterface dialog
, int which
) {
637 dialog
= builder
.create();
640 case DIALOG_SHORT_WAIT
: {
641 ProgressDialog working_dialog
= new ProgressDialog(this);
642 working_dialog
.setMessage(getResources().getString(
643 R
.string
.wait_a_moment
));
644 working_dialog
.setIndeterminate(true
);
645 working_dialog
.setCancelable(false
);
646 dialog
= working_dialog
;
649 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
650 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
651 getString(R
.string
.actionbar_upload_from_apps
) };
652 builder
= new AlertDialog
.Builder(this);
653 builder
.setTitle(R
.string
.actionbar_upload
);
654 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
655 public void onClick(DialogInterface dialog
, int item
) {
658 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
659 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
661 // TODO create and handle new fragment LocalFileListFragment
663 } else if (item
== 1) {
664 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
665 action
= action
.setType("*/*")
666 .addCategory(Intent
.CATEGORY_OPENABLE
);
667 startActivityForResult(
668 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
669 ACTION_SELECT_CONTENT_FROM_APPS
);
673 dialog
= builder
.create();
676 case DIALOG_SSL_VALIDATOR
: {
677 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
680 case DIALOG_CERT_NOT_SAVED
: {
681 builder
= new AlertDialog
.Builder(this);
682 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
683 builder
.setCancelable(false
);
684 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
686 public void onClick(DialogInterface dialog
, int which
) {
690 dialog
= builder
.create();
702 * Translates a content URI of an image to a physical path
704 * @param uri The URI to resolve
705 * @return The path to the image or null if it could not be found
707 public String
getPath(Uri uri
) {
708 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
709 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
710 if (cursor
!= null
) {
711 int column_index
= cursor
712 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
713 cursor
.moveToFirst();
714 return cursor
.getString(column_index
);
720 * Pushes a directory to the drop down list
721 * @param directory to push
722 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
724 public void pushDirname(OCFile directory
) {
725 if(!directory
.isDirectory()){
726 throw new IllegalArgumentException("Only directories may be pushed!");
728 mDirectories
.insert(directory
.getFileName(), 0);
729 mCurrentDir
= directory
;
733 * Pops a directory name from the drop down list
734 * @return True, unless the stack is empty
736 public boolean popDirname() {
737 mDirectories
.remove(mDirectories
.getItem(0));
738 return !mDirectories
.isEmpty();
741 private class DirectoryCreator
implements Runnable
{
742 private String mTargetPath
;
743 private Account mAccount
;
744 private Handler mHandler
;
746 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
747 mTargetPath
= targetPath
;
754 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
755 boolean created
= wdc
.createDirectory(mTargetPath
);
757 mHandler
.post(new Runnable() {
760 dismissDialog(DIALOG_SHORT_WAIT
);
762 // Save new directory in local database
763 OCFile newDir
= new OCFile(mTargetPath
);
764 newDir
.setMimetype("DIR");
765 newDir
.setParentId(mCurrentDir
.getFileId());
766 mStorageManager
.saveFile(newDir
);
768 // Display the new folder right away
769 mFileList
.listDirectory();
774 mHandler
.post(new Runnable() {
777 dismissDialog(DIALOG_SHORT_WAIT
);
779 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
782 } catch (NotFoundException e
) {
783 Log
.e(TAG
, "Error while trying to show fail message " , e
);
792 // Custom array adapter to override text colors
793 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
795 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
799 public View
getView(int position
, View convertView
, ViewGroup parent
) {
800 View v
= super.getView(position
, convertView
, parent
);
802 ((TextView
) v
).setTextColor(getResources().getColorStateList(
803 android
.R
.color
.white
));
807 public View
getDropDownView(int position
, View convertView
,
809 View v
= super.getDropDownView(position
, convertView
, parent
);
811 ((TextView
) v
).setTextColor(getResources().getColorStateList(
812 android
.R
.color
.white
));
819 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
822 * {@link BroadcastReceiver} to enable syncing feedback in UI
825 public void onReceive(Context context
, Intent intent
) {
826 boolean inProgress
= intent
.getBooleanExtra(
827 FileSyncService
.IN_PROGRESS
, false
);
828 String accountName
= intent
829 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
831 Log
.d("FileDisplay", "sync of account " + accountName
832 + " is in_progress: " + inProgress
);
834 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
836 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
838 boolean fillBlankRoot
= false
;
839 if (mCurrentDir
== null
) {
840 mCurrentDir
= mStorageManager
.getFileByPath("/");
841 fillBlankRoot
= (mCurrentDir
!= null
);
844 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
847 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
848 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
849 .findFragmentById(R
.id
.fileList
);
850 if (fileListFragment
!= null
) {
851 fileListFragment
.listDirectory(mCurrentDir
);
855 setSupportProgressBarIndeterminateVisibility(inProgress
);
859 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncService
.SYNC_RESULT
);
860 if (synchResult
!= null
) {
861 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
862 mLastSslUntrustedServerResult
= synchResult
;
863 showDialog(DIALOG_SSL_VALIDATOR
);
870 private class UploadFinishReceiver
extends BroadcastReceiver
{
872 * Once the file upload has finished -> update view
873 * @author David A. Velasco
874 * {@link BroadcastReceiver} to enable upload feedback in UI
877 public void onReceive(Context context
, Intent intent
) {
878 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
879 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
880 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
881 boolean isDescendant
= (mCurrentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
882 if (sameAccount
&& isDescendant
) {
883 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
884 if (fileListFragment
!= null
) {
885 fileListFragment
.listDirectory();
894 * Once the file download has finished -> update view
896 private class DownloadFinishReceiver
extends BroadcastReceiver
{
898 public void onReceive(Context context
, Intent intent
) {
899 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
900 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
901 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
902 boolean isDescendant
= (mCurrentDir
!= null
) && (downloadedRemotePath
!= null
) && (downloadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
903 if (sameAccount
&& isDescendant
) {
904 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
905 if (fileListFragment
!= null
) {
906 fileListFragment
.listDirectory();
919 public DataStorageManager
getStorageManager() {
920 return mStorageManager
;
928 public void onDirectoryClick(OCFile directory
) {
929 pushDirname(directory
);
930 ActionBar actionBar
= getSupportActionBar();
931 actionBar
.setDisplayHomeAsUpEnabled(true
);
934 // Resets the FileDetailsFragment on Tablets so that it always displays
935 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
936 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
937 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
938 transaction
.remove(fileDetails
);
939 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
940 transaction
.commit();
950 public void onFileClick(OCFile file
) {
952 // If we are on a large device -> update fragment
954 // 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'
955 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
956 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
957 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
958 transaction
.commit();
960 } else { // small or medium screen device -> new Activity
961 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
962 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
963 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
964 startActivity(showDetailsIntent
);
973 public OCFile
getInitialDirectory() {
982 public void onFileStateChanged() {
983 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
984 if (fileListFragment
!= null
) {
985 fileListFragment
.listDirectory();
994 public FileDownloaderBinder
getFileDownloaderBinder() {
995 return mDownloaderBinder
;
1003 public FileUploaderBinder
getFileUploaderBinder() {
1004 return mUploaderBinder
;
1008 /** Defines callbacks for service binding, passed to bindService() */
1009 private class ListServiceConnection
implements ServiceConnection
{
1012 public void onServiceConnected(ComponentName component
, IBinder service
) {
1013 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1014 Log
.d(TAG
, "Download service connected");
1015 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1016 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1017 Log
.d(TAG
, "Upload service connected");
1018 mUploaderBinder
= (FileUploaderBinder
) service
;
1022 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1023 if (mFileList
!= null
)
1024 mFileList
.listDirectory();
1026 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1027 if (fragment
!= null
)
1028 fragment
.updateFileDetails(false
);
1033 public void onServiceDisconnected(ComponentName component
) {
1034 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1035 Log
.d(TAG
, "Download service disconnected");
1036 mDownloaderBinder
= null
;
1037 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1038 Log
.d(TAG
, "Upload service disconnected");
1039 mUploaderBinder
= null
;
1047 * Launch an intent to request the PIN code to the user before letting him use the app
1049 private void requestPinCode() {
1050 boolean pinStart
= false
;
1051 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1052 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1054 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1055 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1062 public void onSavedCertificate() {
1063 startSynchronization();
1068 public void onFailedSavingCertificate() {
1069 showDialog(DIALOG_CERT_NOT_SAVED
);
1074 * Updates the view associated to the activity after the finish of some operation over files
1075 * in the current account.
1077 * @param operation Removal operation performed.
1078 * @param result Result of the removal.
1081 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1082 if (operation
instanceof RemoveFileOperation
) {
1083 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1085 } else if (operation
instanceof RenameFileOperation
) {
1086 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1088 } else if (operation
instanceof SynchronizeFileOperation
) {
1089 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1095 * Updates the view associated to the activity after the finish of an operation trying to remove a
1098 * @param operation Removal operation performed.
1099 * @param result Result of the removal.
1101 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1102 dismissDialog(DIALOG_SHORT_WAIT
);
1103 if (result
.isSuccess()) {
1104 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1106 OCFile removedFile
= operation
.getFile();
1108 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1109 if (details
!= null
&& removedFile
.equals(details
.getDisplayedFile()) ) {
1110 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
1111 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1112 transaction
.commit();
1115 if (mStorageManager
.getFileById(removedFile
.getParentId()).equals(mCurrentDir
)) {
1116 mFileList
.listDirectory();
1120 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1122 if (result
.isSslRecoverableException()) {
1123 mLastSslUntrustedServerResult
= result
;
1124 showDialog(DIALOG_SSL_VALIDATOR
);
1130 * Updates the view associated to the activity after the finish of an operation trying to rename a
1133 * @param operation Renaming operation performed.
1134 * @param result Result of the renaming.
1136 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1137 dismissDialog(DIALOG_SHORT_WAIT
);
1138 OCFile renamedFile
= operation
.getFile();
1139 if (result
.isSuccess()) {
1141 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1142 if (details
!= null
&& renamedFile
.equals(details
.getDisplayedFile()) ) {
1143 details
.updateFileDetails(renamedFile
, AccountUtils
.getCurrentOwnCloudAccount(this));
1146 if (mStorageManager
.getFileById(renamedFile
.getParentId()).equals(mCurrentDir
)) {
1147 mFileList
.listDirectory();
1151 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1152 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1154 // TODO throw again the new rename dialog
1156 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1158 if (result
.isSslRecoverableException()) {
1159 mLastSslUntrustedServerResult
= result
;
1160 showDialog(DIALOG_SSL_VALIDATOR
);
1167 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1168 dismissDialog(DIALOG_SHORT_WAIT
);
1169 OCFile syncedFile
= operation
.getLocalFile();
1170 if (!result
.isSuccess()) {
1171 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1172 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1173 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1174 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
1178 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1183 if (operation
.transferWasRequested()) {
1184 mFileList
.listDirectory();
1185 onTransferStateChanged(syncedFile
, true
, true
);
1188 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1199 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1200 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1201 if (fileListFragment != null) {
1202 fileListFragment.listDirectory();
1205 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1206 if (details
!= null
&& file
.equals(details
.getDisplayedFile()) ) {
1207 if (downloading
|| uploading
) {
1208 details
.updateFileDetails(file
, AccountUtils
.getCurrentOwnCloudAccount(this));
1210 details
.updateFileDetails(downloading
|| uploading
);