1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 package com
.owncloud
.android
.ui
.activity
;
24 import android
.accounts
.Account
;
25 import android
.app
.AlertDialog
;
26 import android
.app
.AlertDialog
.Builder
;
27 import android
.app
.Dialog
;
28 import android
.app
.ProgressDialog
;
29 import android
.content
.BroadcastReceiver
;
30 import android
.content
.ComponentName
;
31 import android
.content
.ContentResolver
;
32 import android
.content
.Context
;
33 import android
.content
.DialogInterface
;
34 import android
.content
.DialogInterface
.OnClickListener
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SharedPreferences
.Editor
;
40 import android
.content
.pm
.PackageInfo
;
41 import android
.content
.pm
.PackageManager
.NameNotFoundException
;
42 import android
.content
.res
.Resources
.NotFoundException
;
43 import android
.database
.Cursor
;
44 import android
.graphics
.Bitmap
;
45 import android
.graphics
.drawable
.BitmapDrawable
;
46 import android
.net
.Uri
;
47 import android
.os
.Bundle
;
48 import android
.os
.Handler
;
49 import android
.os
.IBinder
;
50 import android
.preference
.PreferenceManager
;
51 import android
.provider
.MediaStore
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.util
.Log
;
54 import android
.view
.View
;
55 import android
.view
.ViewGroup
;
56 import android
.widget
.ArrayAdapter
;
57 import android
.widget
.EditText
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.ActionBar
;
62 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
63 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
64 import com
.actionbarsherlock
.view
.Menu
;
65 import com
.actionbarsherlock
.view
.MenuInflater
;
66 import com
.actionbarsherlock
.view
.MenuItem
;
67 import com
.actionbarsherlock
.view
.Window
;
68 import com
.owncloud
.android
.AccountUtils
;
69 import com
.owncloud
.android
.Log_OC
;
70 import com
.owncloud
.android
.R
;
71 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
72 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
73 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
74 import com
.owncloud
.android
.datamodel
.OCFile
;
75 import com
.owncloud
.android
.files
.services
.FileDownloader
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
77 import com
.owncloud
.android
.files
.services
.FileObserverService
;
78 import com
.owncloud
.android
.files
.services
.FileUploader
;
79 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
80 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
81 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
82 import com
.owncloud
.android
.operations
.RemoteOperation
;
83 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
84 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
89 import com
.owncloud
.android
.ui
.dialog
.ChangelogDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
92 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
95 import eu
.alefzero
.webdav
.WebdavClient
;
98 * Displays, what files the user has available in his ownCloud.
100 * @author Bartek Przybylski
104 public class FileDisplayActivity
extends SherlockFragmentActivity
implements OCFileListFragment
.ContainerActivity
,
105 FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, OnRemoteOperationListener
{
107 private ArrayAdapter
<String
> mDirectories
;
108 private OCFile mCurrentDir
= null
;
109 private OCFile mCurrentFile
= null
;
111 private DataStorageManager mStorageManager
;
112 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
113 private UploadFinishReceiver mUploadFinishReceiver
;
114 private DownloadFinishReceiver mDownloadFinishReceiver
;
115 private FileDownloaderBinder mDownloaderBinder
= null
;
116 private FileUploaderBinder mUploaderBinder
= null
;
117 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
118 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
120 private OCFileListFragment mFileList
;
122 private boolean mDualPane
;
124 private static final int DIALOG_SETUP_ACCOUNT
= 0;
125 private static final int DIALOG_CREATE_DIR
= 1;
126 public static final int DIALOG_SHORT_WAIT
= 3;
127 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
128 private static final int DIALOG_SSL_VALIDATOR
= 5;
129 private static final int DIALOG_CERT_NOT_SAVED
= 6;
130 private static final String DIALOG_CHANGELOG_TAG
= "DIALOG_CHANGELOG";
133 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
134 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
135 private static final int ACTION_SELECT_FAILED_INSTANT_UPLOAD
= 2;
137 private static final String TAG
= "FileDisplayActivity";
141 public void onCreate(Bundle savedInstanceState
) {
142 Log_OC
.d(getClass().toString(), "onCreate() start");
143 super.onCreate(savedInstanceState
);
145 /// Load of parameters from received intent
146 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
147 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
149 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
151 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
152 if(savedInstanceState
!= null
) {
153 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
154 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
157 if (!AccountUtils
.accountsAreSetup(this)) {
158 /// no account available: FORCE ACCOUNT CREATION
159 mStorageManager
= null
;
160 createFirstAccount();
162 } else { // / at least an account is available
164 initDataFromCurrentAccount(); // it checks mCurrentDir and
165 // mCurrentFile with the current
170 mUploadConnection
= new ListServiceConnection();
171 mDownloadConnection
= new ListServiceConnection();
172 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
173 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
175 // PIN CODE request ; best location is to decide, let's try this first
176 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
181 Intent observer_intent
= new Intent(this, FileObserverService
.class);
182 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
183 startService(observer_intent
);
187 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
189 // Drop-down navigation
190 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
191 OCFile currFile
= mCurrentDir
;
192 while (currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
193 mDirectories
.add(currFile
.getFileName());
194 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
196 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
198 // Inflate and set the layout view
199 setContentView(R
.layout
.files
);
200 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
201 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
203 initFileDetailsInDualPane();
207 ActionBar actionBar
= getSupportActionBar();
208 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
209 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
210 actionBar
.setDisplayShowTitleEnabled(false
);
211 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
212 actionBar
.setListNavigationCallbacks(mDirectories
, this);
213 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
216 // show changelog, if needed
219 Log_OC
.d(getClass().toString(), "onCreate() end");
224 * Shows a dialog with the change log of the current version after each app update
226 * TODO make it permanent; by now, only to advice the workaround app for 4.1.x
228 private void showChangeLog() {
229 if (android
.os
.Build
.VERSION
.SDK_INT
== android
.os
.Build
.VERSION_CODES
.JELLY_BEAN
) {
230 final String KEY_VERSION
= "version";
231 SharedPreferences sharedPref
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
232 int currentVersionNumber
= 0;
233 int savedVersionNumber
= sharedPref
.getInt(KEY_VERSION
, 0);
235 PackageInfo pi
= getPackageManager().getPackageInfo(getPackageName(), 0);
236 currentVersionNumber
= pi
.versionCode
;
237 } catch (Exception e
) {}
239 if (currentVersionNumber
> savedVersionNumber
) {
240 ChangelogDialog
.newInstance(true
).show(getSupportFragmentManager(), DIALOG_CHANGELOG_TAG
);
241 Editor editor
= sharedPref
.edit();
242 editor
.putInt(KEY_VERSION
, currentVersionNumber
);
250 * Launches the account creation activity. To use when no ownCloud account is available
252 private void createFirstAccount() {
253 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
254 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
255 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
260 * Load of state dependent of the existence of an ownCloud account
262 private void initDataFromCurrentAccount() {
263 /// Storage manager initialization - access to local database
264 mStorageManager
= new FileDataStorageManager(
265 AccountUtils
.getCurrentOwnCloudAccount(this),
266 getContentResolver());
268 /// Check if mCurrentDir is a directory
269 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
270 mCurrentFile
= mCurrentDir
;
271 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
274 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
275 if (mCurrentDir
!= null
) {
276 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
278 if (mCurrentFile
!= null
) {
279 if (mCurrentFile
.fileExists()) {
280 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
281 } // 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
284 /// Default to root if mCurrentDir was not found
285 if (mCurrentDir
== null
) {
286 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
291 private void initFileDetailsInDualPane() {
292 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
293 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
294 if (mCurrentFile
!= null
) {
295 transaction
.replace(R
.id
.file_details_container
,
296 new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)),
297 FileDetailFragment
.FTAG
); // empty FileDetailFragment
300 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
),
301 FileDetailFragment
.FTAG
); // empty FileDetailFragment
303 transaction
.commit();
309 public void onDestroy() {
311 if (mDownloadConnection
!= null
)
312 unbindService(mDownloadConnection
);
313 if (mUploadConnection
!= null
)
314 unbindService(mUploadConnection
);
319 public boolean onCreateOptionsMenu(Menu menu
) {
320 MenuInflater inflater
= getSherlock().getMenuInflater();
321 inflater
.inflate(R
.menu
.menu
, menu
);
326 public boolean onOptionsItemSelected(MenuItem item
) {
327 boolean retval
= true
;
328 switch (item
.getItemId()) {
329 case R
.id
.createDirectoryItem
: {
330 showDialog(DIALOG_CREATE_DIR
);
333 case R
.id
.startSync
: {
334 startSynchronization();
337 case R
.id
.action_upload
: {
338 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
341 case R
.id
.action_settings
: {
342 Intent settingsIntent
= new Intent(this, Preferences
.class);
343 startActivity(settingsIntent
);
346 case android
.R
.id
.home
: {
347 if (mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0) {
353 retval
= super.onOptionsItemSelected(item
);
358 private void startSynchronization() {
359 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
360 Bundle bundle
= new Bundle();
361 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
362 ContentResolver
.requestSync(
363 AccountUtils
.getCurrentOwnCloudAccount(this),
364 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
369 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
370 int i
= itemPosition
;
374 // the next operation triggers a new call to this method, but it's necessary to
375 // ensure that the name exposed in the action bar is the current directory when the
376 // user selected it in the navigation list
377 if (itemPosition
!= 0)
378 getSupportActionBar().setSelectedNavigationItem(0);
383 * Called, when the user selected something for uploading
385 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
387 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
388 && (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
389 requestSimpleUpload(data
, resultCode
);
391 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
392 && (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
393 requestMultipleUpload(data
, resultCode
);
398 private void requestMultipleUpload(Intent data
, int resultCode
) {
399 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
400 if (filePaths
!= null
) {
401 String
[] remotePaths
= new String
[filePaths
.length
];
402 String remotePathBase
= "";
403 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
404 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
406 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
407 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
408 for (int j
= 0; j
< remotePaths
.length
; j
++) {
409 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
412 Intent i
= new Intent(this, FileUploader
.class);
413 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
414 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
415 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
416 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
417 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
418 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
422 Log_OC
.d("FileDisplay", "User clicked on 'Update' with no selection");
423 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
430 private void requestSimpleUpload(Intent data
, int resultCode
) {
431 String filepath
= null
;
433 Uri selectedImageUri
= data
.getData();
435 String filemanagerstring
= selectedImageUri
.getPath();
436 String selectedImagePath
= getPath(selectedImageUri
);
438 if (selectedImagePath
!= null
)
439 filepath
= selectedImagePath
;
441 filepath
= filemanagerstring
;
443 } catch (Exception e
) {
444 Log_OC
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
448 if (filepath
== null
) {
449 Log_OC
.e("FileDisplay", "Couldnt resolve path to file");
450 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
456 Intent i
= new Intent(this, FileUploader
.class);
457 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
458 String remotepath
= new String();
459 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
460 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
462 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
463 remotepath
+= OCFile
.PATH_SEPARATOR
;
464 remotepath
+= new File(filepath
).getName();
466 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
467 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
468 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
469 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
470 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
476 public void onBackPressed() {
477 if (mDirectories
.getCount() <= 1) {
482 mFileList
.onNavigateUp();
483 mCurrentDir
= mFileList
.getCurrentFile();
486 // Resets the FileDetailsFragment on Tablets so that it always
488 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
489 FileDetailFragment
.FTAG
);
490 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
491 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
492 transaction
.remove(fileDetails
);
493 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
),
494 FileDetailFragment
.FTAG
);
495 transaction
.commit();
499 if (mCurrentDir
.getParentId() == 0) {
500 ActionBar actionBar
= getSupportActionBar();
501 actionBar
.setDisplayHomeAsUpEnabled(false
);
506 protected void onSaveInstanceState(Bundle outState
) {
507 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
508 Log_OC
.d(getClass().toString(), "onSaveInstanceState() start");
509 super.onSaveInstanceState(outState
);
510 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
512 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
513 if (fragment
!= null
) {
514 OCFile file
= fragment
.getDisplayedFile();
516 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
520 Log_OC
.d(getClass().toString(), "onSaveInstanceState() end");
524 protected void onResume() {
525 Log_OC
.d(getClass().toString(), "onResume() start");
528 if (AccountUtils
.accountsAreSetup(this)) {
530 if (mStorageManager
== null
) {
531 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
532 initDataFromCurrentAccount();
534 initFileDetailsInDualPane();
538 // Listen for sync messages
539 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
540 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
541 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
543 // Listen for upload messages
544 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
545 mUploadFinishReceiver
= new UploadFinishReceiver();
546 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
548 // Listen for download messages
549 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
550 mDownloadFinishReceiver
= new DownloadFinishReceiver();
551 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
553 // List current directory
554 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
558 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
559 showDialog(DIALOG_SETUP_ACCOUNT
);
562 Log_OC
.d(getClass().toString(), "onResume() end");
567 protected void onPause() {
568 Log_OC
.d(getClass().toString(), "onPause() start");
570 if (mSyncBroadcastReceiver
!= null
) {
571 unregisterReceiver(mSyncBroadcastReceiver
);
572 mSyncBroadcastReceiver
= null
;
574 if (mUploadFinishReceiver
!= null
) {
575 unregisterReceiver(mUploadFinishReceiver
);
576 mUploadFinishReceiver
= null
;
578 if (mDownloadFinishReceiver
!= null
) {
579 unregisterReceiver(mDownloadFinishReceiver
);
580 mDownloadFinishReceiver
= null
;
582 if (!AccountUtils
.accountsAreSetup(this)) {
583 dismissDialog(DIALOG_SETUP_ACCOUNT
);
586 Log_OC
.d(getClass().toString(), "onPause() end");
591 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
592 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
593 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
599 protected Dialog
onCreateDialog(int id
) {
600 Dialog dialog
= null
;
601 AlertDialog
.Builder builder
;
603 case DIALOG_SETUP_ACCOUNT
: {
604 builder
= new AlertDialog
.Builder(this);
605 builder
.setTitle(R
.string
.main_tit_accsetup
);
606 builder
.setMessage(R
.string
.main_wrn_accsetup
);
607 builder
.setCancelable(false
);
608 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
609 public void onClick(DialogInterface dialog
, int which
) {
610 createFirstAccount();
614 String message
= String
.format(getString(R
.string
.common_exit
), getString(R
.string
.app_name
));
615 builder
.setNegativeButton(message
, new OnClickListener() {
616 public void onClick(DialogInterface dialog
, int which
) {
621 //builder.setNegativeButton(android.R.string.cancel, this);
622 dialog
= builder
.create();
625 case DIALOG_CREATE_DIR
: {
626 builder
= new Builder(this);
627 final EditText dirNameInput
= new EditText(getBaseContext());
628 builder
.setView(dirNameInput
);
629 builder
.setTitle(R
.string
.uploader_info_dirname
);
630 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
631 dirNameInput
.setTextColor(typed_color
);
632 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
633 public void onClick(DialogInterface dialog
, int which
) {
634 String directoryName
= dirNameInput
.getText().toString();
635 if (directoryName
.trim().length() == 0) {
640 // Figure out the path where the dir needs to be created
642 if (mCurrentDir
== null
) {
643 // this is just a patch; we should ensure that
644 // mCurrentDir never is null
645 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
646 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
647 mStorageManager
.saveFile(file
);
649 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
651 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
654 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
655 Thread thread
= new Thread(new DirectoryCreator(path
, AccountUtils
656 .getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
661 showDialog(DIALOG_SHORT_WAIT
);
664 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
665 public void onClick(DialogInterface dialog
, int which
) {
669 dialog
= builder
.create();
672 case DIALOG_SHORT_WAIT
: {
673 ProgressDialog working_dialog
= new ProgressDialog(this);
674 working_dialog
.setMessage(getResources().getString(R
.string
.wait_a_moment
));
675 working_dialog
.setIndeterminate(true
);
676 working_dialog
.setCancelable(false
);
677 dialog
= working_dialog
;
680 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
681 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
682 getString(R
.string
.actionbar_upload_from_apps
), getString(R
.string
.actionbar_failed_instant_upload
) };
683 builder
= new AlertDialog
.Builder(this);
684 builder
.setTitle(R
.string
.actionbar_upload
);
685 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
686 public void onClick(DialogInterface dialog
, int item
) {
689 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
690 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
,
691 AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this));
692 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
694 // TODO create and handle new fragment
695 // LocalFileListFragment
697 } else if (item
== 1) {
698 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
699 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
700 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
701 ACTION_SELECT_CONTENT_FROM_APPS
);
702 } else if (item
== 2) {
703 Account account
= AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this);
704 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
705 action
.putExtra(FileUploader
.KEY_ACCOUNT
, account
);
706 startActivity(action
);
710 dialog
= builder
.create();
713 case DIALOG_SSL_VALIDATOR
: {
714 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
717 case DIALOG_CERT_NOT_SAVED
: {
718 builder
= new AlertDialog
.Builder(this);
719 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
720 builder
.setCancelable(false
);
721 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
723 public void onClick(DialogInterface dialog
, int which
) {
727 dialog
= builder
.create();
739 * Translates a content URI of an image to a physical path
741 * @param uri The URI to resolve
742 * @return The path to the image or null if it could not be found
744 public String
getPath(Uri uri
) {
745 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
746 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
747 if (cursor
!= null
) {
748 int column_index
= cursor
.getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
749 cursor
.moveToFirst();
750 return cursor
.getString(column_index
);
756 * Pushes a directory to the drop down list
757 * @param directory to push
758 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
760 public void pushDirname(OCFile directory
) {
761 if(!directory
.isDirectory()){
762 throw new IllegalArgumentException("Only directories may be pushed!");
764 mDirectories
.insert(directory
.getFileName(), 0);
765 mCurrentDir
= directory
;
769 * Pops a directory name from the drop down list
770 * @return True, unless the stack is empty
772 public boolean popDirname() {
773 mDirectories
.remove(mDirectories
.getItem(0));
774 return !mDirectories
.isEmpty();
777 private class DirectoryCreator
implements Runnable
{
778 private String mTargetPath
;
779 private Account mAccount
;
780 private Handler mHandler
;
782 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
783 mTargetPath
= targetPath
;
790 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
791 boolean created
= wdc
.createDirectory(mTargetPath
);
793 mHandler
.post(new Runnable() {
796 dismissDialog(DIALOG_SHORT_WAIT
);
798 // Save new directory in local database
799 OCFile newDir
= new OCFile(mTargetPath
);
800 newDir
.setMimetype("DIR");
801 newDir
.setParentId(mCurrentDir
.getFileId());
802 mStorageManager
.saveFile(newDir
);
804 // Display the new folder right away
805 mFileList
.listDirectory();
810 mHandler
.post(new Runnable() {
813 dismissDialog(DIALOG_SHORT_WAIT
);
815 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
,
819 } catch (NotFoundException e
) {
820 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
829 // Custom array adapter to override text colors
830 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
832 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
836 public View
getView(int position
, View convertView
, ViewGroup parent
) {
837 View v
= super.getView(position
, convertView
, parent
);
839 ((TextView
) v
).setTextColor(getResources().getColorStateList(android
.R
.color
.white
));
843 public View
getDropDownView(int position
, View convertView
, ViewGroup parent
) {
844 View v
= super.getDropDownView(position
, convertView
, parent
);
846 ((TextView
) v
).setTextColor(getResources().getColorStateList(android
.R
.color
.white
));
853 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
856 * {@link BroadcastReceiver} to enable syncing feedback in UI
859 public void onReceive(Context context
, Intent intent
) {
860 boolean inProgress
= intent
.getBooleanExtra(FileSyncService
.IN_PROGRESS
, false
);
861 String accountName
= intent
.getStringExtra(FileSyncService
.ACCOUNT_NAME
);
863 Log_OC
.d("FileDisplay", "sync of account " + accountName
+ " is in_progress: " + inProgress
);
865 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
867 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
869 boolean fillBlankRoot
= false
;
870 if (mCurrentDir
== null
) {
871 mCurrentDir
= mStorageManager
.getFileByPath("/");
872 fillBlankRoot
= (mCurrentDir
!= null
);
875 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath()
876 .equals(synchFolderRemotePath
))) || fillBlankRoot
) {
878 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
879 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
880 .findFragmentById(R
.id
.fileList
);
881 if (fileListFragment
!= null
) {
882 fileListFragment
.listDirectory(mCurrentDir
);
886 setSupportProgressBarIndeterminateVisibility(inProgress
);
887 removeStickyBroadcast(intent
);
891 RemoteOperationResult synchResult
= (RemoteOperationResult
) intent
892 .getSerializableExtra(FileSyncService
.SYNC_RESULT
);
893 if (synchResult
!= null
) {
894 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
895 mLastSslUntrustedServerResult
= synchResult
;
896 showDialog(DIALOG_SSL_VALIDATOR
);
903 private class UploadFinishReceiver
extends BroadcastReceiver
{
905 * Once the file upload has finished -> update view
906 * @author David A. Velasco
907 * {@link BroadcastReceiver} to enable upload feedback in UI
910 public void onReceive(Context context
, Intent intent
) {
911 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
912 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
913 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
914 boolean isDescendant
= (mCurrentDir
!= null
) && (uploadedRemotePath
!= null
)
915 && (uploadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
916 if (sameAccount
&& isDescendant
) {
917 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
918 .findFragmentById(R
.id
.fileList
);
919 if (fileListFragment
!= null
) {
920 fileListFragment
.listDirectory();
929 * Once the file download has finished -> update view
931 private class DownloadFinishReceiver
extends BroadcastReceiver
{
933 public void onReceive(Context context
, Intent intent
) {
934 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
935 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
936 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
937 boolean isDescendant
= (mCurrentDir
!= null
) && (downloadedRemotePath
!= null
)
938 && (downloadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
939 if (sameAccount
&& isDescendant
) {
940 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
941 .findFragmentById(R
.id
.fileList
);
942 if (fileListFragment
!= null
) {
943 fileListFragment
.listDirectory();
956 public DataStorageManager
getStorageManager() {
957 return mStorageManager
;
965 public void onDirectoryClick(OCFile directory
) {
966 pushDirname(directory
);
967 ActionBar actionBar
= getSupportActionBar();
968 actionBar
.setDisplayHomeAsUpEnabled(true
);
971 // Resets the FileDetailsFragment on Tablets so that it always displays
972 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
973 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
974 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
975 transaction
.remove(fileDetails
);
976 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
),
977 FileDetailFragment
.FTAG
);
978 transaction
.commit();
988 public void onFileClick(OCFile file
) {
990 // If we are on a large device -> update fragment
992 // 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'
993 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
995 .replace(R
.id
.file_details_container
,
996 new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)),
997 FileDetailFragment
.FTAG
);
998 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
999 transaction
.commit();
1001 } else { // small or medium screen device -> new Activity
1002 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
1003 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
1004 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
1005 startActivity(showDetailsIntent
);
1014 public OCFile
getInitialDirectory() {
1023 public void onFileStateChanged() {
1024 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(
1026 if (fileListFragment
!= null
) {
1027 fileListFragment
.listDirectory();
1036 public FileDownloaderBinder
getFileDownloaderBinder() {
1037 return mDownloaderBinder
;
1045 public FileUploaderBinder
getFileUploaderBinder() {
1046 return mUploaderBinder
;
1050 /** Defines callbacks for service binding, passed to bindService() */
1051 private class ListServiceConnection
implements ServiceConnection
{
1054 public void onServiceConnected(ComponentName component
, IBinder service
) {
1055 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1056 Log_OC
.d(TAG
, "Download service connected");
1057 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1058 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1059 Log_OC
.d(TAG
, "Upload service connected");
1060 mUploaderBinder
= (FileUploaderBinder
) service
;
1064 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1065 if (mFileList
!= null
)
1066 mFileList
.listDirectory();
1068 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
1069 FileDetailFragment
.FTAG
);
1070 if (fragment
!= null
)
1071 fragment
.updateFileDetails(false
);
1076 public void onServiceDisconnected(ComponentName component
) {
1077 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1078 Log_OC
.d(TAG
, "Download service disconnected");
1079 mDownloaderBinder
= null
;
1080 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1081 Log_OC
.d(TAG
, "Upload service disconnected");
1082 mUploaderBinder
= null
;
1090 * Launch an intent to request the PIN code to the user before letting him use the app
1092 private void requestPinCode() {
1093 boolean pinStart
= false
;
1094 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1095 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1097 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1098 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1105 public void onSavedCertificate() {
1106 startSynchronization();
1110 public void onFailedSavingCertificate() {
1111 showDialog(DIALOG_CERT_NOT_SAVED
);
1116 * Updates the view associated to the activity after the finish of some operation over files
1117 * in the current account.
1119 * @param operation Removal operation performed.
1120 * @param result Result of the removal.
1123 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1124 if (operation
instanceof RemoveFileOperation
) {
1125 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1127 } else if (operation
instanceof RenameFileOperation
) {
1128 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1130 } else if (operation
instanceof SynchronizeFileOperation
) {
1131 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1137 * Updates the view associated to the activity after the finish of an operation trying to remove a
1140 * @param operation Removal operation performed.
1141 * @param result Result of the removal.
1143 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1144 dismissDialog(DIALOG_SHORT_WAIT
);
1145 if (result
.isSuccess()) {
1146 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1148 OCFile removedFile
= operation
.getFile();
1150 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
1151 FileDetailFragment
.FTAG
);
1152 if (details
!= null
&& removedFile
.equals(details
.getDisplayedFile())) {
1153 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
1154 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty
1155 // FileDetailFragment
1156 transaction
.commit();
1159 if (mStorageManager
.getFileById(removedFile
.getParentId()).equals(mCurrentDir
)) {
1160 mFileList
.listDirectory();
1164 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1166 if (result
.isSslRecoverableException()) {
1167 mLastSslUntrustedServerResult
= result
;
1168 showDialog(DIALOG_SSL_VALIDATOR
);
1174 * Updates the view associated to the activity after the finish of an operation trying to rename a
1177 * @param operation Renaming operation performed.
1178 * @param result Result of the renaming.
1180 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1181 dismissDialog(DIALOG_SHORT_WAIT
);
1182 OCFile renamedFile
= operation
.getFile();
1183 if (result
.isSuccess()) {
1185 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
1186 FileDetailFragment
.FTAG
);
1187 if (details
!= null
&& renamedFile
.equals(details
.getDisplayedFile())) {
1188 details
.updateFileDetails(renamedFile
, AccountUtils
.getCurrentOwnCloudAccount(this));
1191 if (mStorageManager
.getFileById(renamedFile
.getParentId()).equals(mCurrentDir
)) {
1192 mFileList
.listDirectory();
1196 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1197 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1199 // TODO throw again the new rename dialog
1201 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1203 if (result
.isSslRecoverableException()) {
1204 mLastSslUntrustedServerResult
= result
;
1205 showDialog(DIALOG_SSL_VALIDATOR
);
1211 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1212 dismissDialog(DIALOG_SHORT_WAIT
);
1213 OCFile syncedFile
= operation
.getLocalFile();
1214 if (!result
.isSuccess()) {
1215 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1216 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1217 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1218 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
1222 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1227 if (operation
.transferWasRequested()) {
1228 mFileList
.listDirectory();
1229 onTransferStateChanged(syncedFile
, true
, true
);
1232 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1243 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1244 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1245 if (fileListFragment != null) {
1246 fileListFragment.listDirectory();
1249 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
1250 FileDetailFragment
.FTAG
);
1251 if (details
!= null
&& file
.equals(details
.getDisplayedFile())) {
1252 if (downloading
|| uploading
) {
1253 details
.updateFileDetails(file
, AccountUtils
.getCurrentOwnCloudAccount(this));
1255 details
.updateFileDetails(downloading
|| uploading
);