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
.graphics
.Bitmap
;
43 import android
.graphics
.drawable
.BitmapDrawable
;
44 import android
.net
.Uri
;
45 import android
.os
.Bundle
;
46 import android
.os
.Handler
;
47 import android
.os
.IBinder
;
48 import android
.preference
.PreferenceManager
;
49 import android
.provider
.MediaStore
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.util
.Log
;
52 import android
.view
.View
;
53 import android
.view
.ViewGroup
;
54 import android
.widget
.ArrayAdapter
;
55 import android
.widget
.EditText
;
56 import android
.widget
.TextView
;
57 import android
.widget
.Toast
;
59 import com
.actionbarsherlock
.app
.ActionBar
;
60 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
61 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
62 import com
.actionbarsherlock
.view
.Menu
;
63 import com
.actionbarsherlock
.view
.MenuInflater
;
64 import com
.actionbarsherlock
.view
.MenuItem
;
65 import com
.actionbarsherlock
.view
.Window
;
66 import com
.owncloud
.android
.AccountUtils
;
67 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
68 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
69 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
70 import com
.owncloud
.android
.datamodel
.OCFile
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
;
72 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
73 import com
.owncloud
.android
.files
.services
.FileObserverService
;
74 import com
.owncloud
.android
.files
.services
.FileUploader
;
75 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
76 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
77 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
78 import com
.owncloud
.android
.operations
.RemoteOperation
;
79 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
80 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
81 import com
.owncloud
.android
.operations
.RenameFileOperation
;
82 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
83 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
84 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
85 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
86 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
87 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
88 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
90 import com
.owncloud
.android
.R
;
91 import eu
.alefzero
.webdav
.WebdavClient
;
94 * Displays, what files the user has available in his ownCloud.
96 * @author Bartek Przybylski
100 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
101 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, OnRemoteOperationListener
{
103 private ArrayAdapter
<String
> mDirectories
;
104 private OCFile mCurrentDir
= null
;
105 private OCFile mCurrentFile
= null
;
107 private DataStorageManager mStorageManager
;
108 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
109 private UploadFinishReceiver mUploadFinishReceiver
;
110 private DownloadFinishReceiver mDownloadFinishReceiver
;
111 private FileDownloaderBinder mDownloaderBinder
= null
;
112 private FileUploaderBinder mUploaderBinder
= null
;
113 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
114 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
116 private OCFileListFragment mFileList
;
118 private boolean mDualPane
;
120 private static final int DIALOG_SETUP_ACCOUNT
= 0;
121 private static final int DIALOG_CREATE_DIR
= 1;
122 private static final int DIALOG_ABOUT_APP
= 2;
123 public static final int DIALOG_SHORT_WAIT
= 3;
124 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
125 private static final int DIALOG_SSL_VALIDATOR
= 5;
126 private static final int DIALOG_CERT_NOT_SAVED
= 6;
129 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
130 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
132 private static final String TAG
= "FileDisplayActivity";
134 private static int[] mMenuIdentifiersToPatch
= {R
.id
.about_app
};
137 public void onCreate(Bundle savedInstanceState
) {
138 Log
.d(getClass().toString(), "onCreate() start");
139 super.onCreate(savedInstanceState
);
141 /// Load of parameters from received intent
142 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
143 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
145 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
147 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
148 if(savedInstanceState
!= null
) {
149 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
150 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
153 if (!AccountUtils
.accountsAreSetup(this)) {
154 /// no account available: FORCE ACCOUNT CREATION
155 mStorageManager
= null
;
156 createFirstAccount();
158 } else { /// at least an account is available
160 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
164 mUploadConnection
= new ListServiceConnection();
165 mDownloadConnection
= new ListServiceConnection();
166 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
167 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
169 // PIN CODE request ; best location is to decide, let's try this first
170 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
175 Intent observer_intent
= new Intent(this, FileObserverService
.class);
176 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
177 startService(observer_intent
);
181 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
183 // Drop-down navigation
184 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
185 OCFile currFile
= mCurrentDir
;
186 while(currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
187 mDirectories
.add(currFile
.getFileName());
188 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
190 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
192 // Inflate and set the layout view
193 setContentView(R
.layout
.files
);
194 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
195 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
197 initFileDetailsInDualPane();
201 ActionBar actionBar
= getSupportActionBar();
202 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
203 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
204 actionBar
.setDisplayShowTitleEnabled(false
);
205 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
206 actionBar
.setListNavigationCallbacks(mDirectories
, this);
207 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
209 Log
.d(getClass().toString(), "onCreate() end");
214 * Launches the account creation activity. To use when no ownCloud account is available
216 private void createFirstAccount() {
217 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
218 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
219 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
224 * Load of state dependent of the existence of an ownCloud account
226 private void initDataFromCurrentAccount() {
227 /// Storage manager initialization - access to local database
228 mStorageManager
= new FileDataStorageManager(
229 AccountUtils
.getCurrentOwnCloudAccount(this),
230 getContentResolver());
232 /// Check if mCurrentDir is a directory
233 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
234 mCurrentFile
= mCurrentDir
;
235 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
238 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
239 if (mCurrentDir
!= null
) {
240 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
242 if (mCurrentFile
!= null
) {
243 if (mCurrentFile
.fileExists()) {
244 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
245 } // 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
248 /// Default to root if mCurrentDir was not found
249 if (mCurrentDir
== null
) {
250 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
255 private void initFileDetailsInDualPane() {
256 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
257 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
258 if (mCurrentFile
!= null
) {
259 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
); // empty FileDetailFragment
262 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
264 transaction
.commit();
270 public void onDestroy() {
272 if (mDownloadConnection
!= null
)
273 unbindService(mDownloadConnection
);
274 if (mUploadConnection
!= null
)
275 unbindService(mUploadConnection
);
280 public boolean onCreateOptionsMenu(Menu menu
) {
281 MenuInflater inflater
= getSherlock().getMenuInflater();
282 inflater
.inflate(R
.menu
.menu
, menu
);
284 patchHiddenAccents(menu
);
290 * Workaround for this: <a href="http://code.google.com/p/android/issues/detail?id=3974">http://code.google.com/p/android/issues/detail?id=3974</a>
292 * @param menu Menu to patch
294 private void patchHiddenAccents(Menu menu
) {
295 for (int i
= 0; i
< mMenuIdentifiersToPatch
.length
; i
++) {
296 MenuItem aboutItem
= menu
.findItem(mMenuIdentifiersToPatch
[i
]);
297 if (aboutItem
!= null
&& aboutItem
.getIcon() instanceof BitmapDrawable
) {
298 // Clip off the bottom three (density independent) pixels of transparent padding
299 Bitmap original
= ((BitmapDrawable
) aboutItem
.getIcon()).getBitmap();
300 float scale
= getResources().getDisplayMetrics().density
;
301 int clippedHeight
= (int) (original
.getHeight() - (3 * scale
));
302 Bitmap scaled
= Bitmap
.createBitmap(original
, 0, 0, original
.getWidth(), clippedHeight
);
303 aboutItem
.setIcon(new BitmapDrawable(getResources(), scaled
));
310 public boolean onOptionsItemSelected(MenuItem item
) {
311 boolean retval
= true
;
312 switch (item
.getItemId()) {
313 case R
.id
.createDirectoryItem
: {
314 showDialog(DIALOG_CREATE_DIR
);
317 case R
.id
.startSync
: {
318 startSynchronization();
321 case R
.id
.action_upload
: {
322 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
325 case R
.id
.action_settings
: {
326 Intent settingsIntent
= new Intent(this, Preferences
.class);
327 startActivity(settingsIntent
);
330 case R
.id
.about_app
: {
331 showDialog(DIALOG_ABOUT_APP
);
334 case android
.R
.id
.home
: {
335 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
341 retval
= super.onOptionsItemSelected(item
);
346 private void startSynchronization() {
347 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
348 Bundle bundle
= new Bundle();
349 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
350 ContentResolver
.requestSync(
351 AccountUtils
.getCurrentOwnCloudAccount(this),
352 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
357 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
358 int i
= itemPosition
;
362 // the next operation triggers a new call to this method, but it's necessary to
363 // ensure that the name exposed in the action bar is the current directory when the
364 // user selected it in the navigation list
365 if (itemPosition
!= 0)
366 getSupportActionBar().setSelectedNavigationItem(0);
371 * Called, when the user selected something for uploading
373 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
375 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
376 requestSimpleUpload(data
, resultCode
);
378 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
379 requestMultipleUpload(data
, resultCode
);
384 private void requestMultipleUpload(Intent data
, int resultCode
) {
385 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
386 if (filePaths
!= null
) {
387 String
[] remotePaths
= new String
[filePaths
.length
];
388 String remotePathBase
= "";
389 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
390 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
392 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
393 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
394 for (int j
= 0; j
< remotePaths
.length
; j
++) {
395 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
398 Intent i
= new Intent(this, FileUploader
.class);
399 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
400 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
401 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
402 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
403 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
404 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
408 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
409 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
416 private void requestSimpleUpload(Intent data
, int resultCode
) {
417 String filepath
= null
;
419 Uri selectedImageUri
= data
.getData();
421 String filemanagerstring
= selectedImageUri
.getPath();
422 String selectedImagePath
= getPath(selectedImageUri
);
424 if (selectedImagePath
!= null
)
425 filepath
= selectedImagePath
;
427 filepath
= filemanagerstring
;
429 } catch (Exception e
) {
430 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
434 if (filepath
== null
) {
435 Log
.e("FileDisplay", "Couldnt resolve path to file");
436 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
442 Intent i
= new Intent(this, FileUploader
.class);
443 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
444 AccountUtils
.getCurrentOwnCloudAccount(this));
445 String remotepath
= new String();
446 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
447 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
449 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
450 remotepath
+= OCFile
.PATH_SEPARATOR
;
451 remotepath
+= new File(filepath
).getName();
453 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
454 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
455 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
456 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
457 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
463 public void onBackPressed() {
464 if (mDirectories
.getCount() <= 1) {
469 mFileList
.onNavigateUp();
470 mCurrentDir
= mFileList
.getCurrentFile();
473 // Resets the FileDetailsFragment on Tablets so that it always displays
474 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
475 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
476 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
477 transaction
.remove(fileDetails
);
478 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
479 transaction
.commit();
483 if(mCurrentDir
.getParentId() == 0){
484 ActionBar actionBar
= getSupportActionBar();
485 actionBar
.setDisplayHomeAsUpEnabled(false
);
490 protected void onSaveInstanceState(Bundle outState
) {
491 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
492 Log
.d(getClass().toString(), "onSaveInstanceState() start");
493 super.onSaveInstanceState(outState
);
494 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
496 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
497 if (fragment
!= null
) {
498 OCFile file
= fragment
.getDisplayedFile();
500 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
504 Log
.d(getClass().toString(), "onSaveInstanceState() end");
508 protected void onResume() {
509 Log
.d(getClass().toString(), "onResume() start");
512 if (AccountUtils
.accountsAreSetup(this)) {
514 if (mStorageManager
== null
) {
515 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
516 initDataFromCurrentAccount();
518 initFileDetailsInDualPane();
522 // Listen for sync messages
523 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
524 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
525 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
527 // Listen for upload messages
528 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
529 mUploadFinishReceiver
= new UploadFinishReceiver();
530 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
532 // Listen for download messages
533 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
534 mDownloadFinishReceiver
= new DownloadFinishReceiver();
535 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
537 // List current directory
538 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
542 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
543 showDialog(DIALOG_SETUP_ACCOUNT
);
546 Log
.d(getClass().toString(), "onResume() end");
551 protected void onPause() {
552 Log
.d(getClass().toString(), "onPause() start");
554 if (mSyncBroadcastReceiver
!= null
) {
555 unregisterReceiver(mSyncBroadcastReceiver
);
556 mSyncBroadcastReceiver
= null
;
558 if (mUploadFinishReceiver
!= null
) {
559 unregisterReceiver(mUploadFinishReceiver
);
560 mUploadFinishReceiver
= null
;
562 if (mDownloadFinishReceiver
!= null
) {
563 unregisterReceiver(mDownloadFinishReceiver
);
564 mDownloadFinishReceiver
= null
;
566 if (!AccountUtils
.accountsAreSetup(this)) {
567 dismissDialog(DIALOG_SETUP_ACCOUNT
);
570 Log
.d(getClass().toString(), "onPause() end");
575 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
576 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
577 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
583 protected Dialog
onCreateDialog(int id
) {
584 Dialog dialog
= null
;
585 AlertDialog
.Builder builder
;
587 case DIALOG_SETUP_ACCOUNT
: {
588 builder
= new AlertDialog
.Builder(this);
589 builder
.setTitle(R
.string
.main_tit_accsetup
);
590 builder
.setMessage(R
.string
.main_wrn_accsetup
);
591 builder
.setCancelable(false
);
592 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
593 public void onClick(DialogInterface dialog
, int which
) {
594 createFirstAccount();
598 builder
.setNegativeButton(R
.string
.common_exit
, new OnClickListener() {
599 public void onClick(DialogInterface dialog
, int which
) {
604 //builder.setNegativeButton(android.R.string.cancel, this);
605 dialog
= builder
.create();
608 case DIALOG_ABOUT_APP
: {
609 builder
= new AlertDialog
.Builder(this);
610 builder
.setTitle(getString(R
.string
.about_title
));
613 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
614 builder
.setMessage(String
.format(getString(R
.string
.about_message
), pkg
.versionName
));
615 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
616 dialog
= builder
.create();
617 } catch (NameNotFoundException e
) {
620 Log
.e(TAG
, "Error while showing about dialog", e
);
624 case DIALOG_CREATE_DIR
: {
625 builder
= new Builder(this);
626 final EditText dirNameInput
= new EditText(getBaseContext());
627 builder
.setView(dirNameInput
);
628 builder
.setTitle(R
.string
.uploader_info_dirname
);
629 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
630 dirNameInput
.setTextColor(typed_color
);
631 builder
.setPositiveButton(android
.R
.string
.ok
,
632 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 mCurrentDir never is null
644 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
645 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
646 mStorageManager
.saveFile(file
);
648 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
650 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
653 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
654 Thread thread
= new Thread(new DirectoryCreator(path
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
659 showDialog(DIALOG_SHORT_WAIT
);
662 builder
.setNegativeButton(R
.string
.common_cancel
,
663 new OnClickListener() {
664 public void onClick(DialogInterface dialog
, int which
) {
668 dialog
= builder
.create();
671 case DIALOG_SHORT_WAIT
: {
672 ProgressDialog working_dialog
= new ProgressDialog(this);
673 working_dialog
.setMessage(getResources().getString(
674 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
) };
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
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this));
691 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
693 // TODO create and handle new fragment LocalFileListFragment
695 } else if (item
== 1) {
696 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
697 action
= action
.setType("*/*")
698 .addCategory(Intent
.CATEGORY_OPENABLE
);
699 startActivityForResult(
700 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
701 ACTION_SELECT_CONTENT_FROM_APPS
);
705 dialog
= builder
.create();
708 case DIALOG_SSL_VALIDATOR
: {
709 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
712 case DIALOG_CERT_NOT_SAVED
: {
713 builder
= new AlertDialog
.Builder(this);
714 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
715 builder
.setCancelable(false
);
716 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
718 public void onClick(DialogInterface dialog
, int which
) {
722 dialog
= builder
.create();
734 * Translates a content URI of an image to a physical path
736 * @param uri The URI to resolve
737 * @return The path to the image or null if it could not be found
739 public String
getPath(Uri uri
) {
740 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
741 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
742 if (cursor
!= null
) {
743 int column_index
= cursor
744 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
745 cursor
.moveToFirst();
746 return cursor
.getString(column_index
);
752 * Pushes a directory to the drop down list
753 * @param directory to push
754 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
756 public void pushDirname(OCFile directory
) {
757 if(!directory
.isDirectory()){
758 throw new IllegalArgumentException("Only directories may be pushed!");
760 mDirectories
.insert(directory
.getFileName(), 0);
761 mCurrentDir
= directory
;
765 * Pops a directory name from the drop down list
766 * @return True, unless the stack is empty
768 public boolean popDirname() {
769 mDirectories
.remove(mDirectories
.getItem(0));
770 return !mDirectories
.isEmpty();
773 private class DirectoryCreator
implements Runnable
{
774 private String mTargetPath
;
775 private Account mAccount
;
776 private Handler mHandler
;
778 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
779 mTargetPath
= targetPath
;
786 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
787 boolean created
= wdc
.createDirectory(mTargetPath
);
789 mHandler
.post(new Runnable() {
792 dismissDialog(DIALOG_SHORT_WAIT
);
794 // Save new directory in local database
795 OCFile newDir
= new OCFile(mTargetPath
);
796 newDir
.setMimetype("DIR");
797 newDir
.setParentId(mCurrentDir
.getFileId());
798 mStorageManager
.saveFile(newDir
);
800 // Display the new folder right away
801 mFileList
.listDirectory();
806 mHandler
.post(new Runnable() {
809 dismissDialog(DIALOG_SHORT_WAIT
);
811 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
814 } catch (NotFoundException e
) {
815 Log
.e(TAG
, "Error while trying to show fail message " , e
);
824 // Custom array adapter to override text colors
825 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
827 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
831 public View
getView(int position
, View convertView
, ViewGroup parent
) {
832 View v
= super.getView(position
, convertView
, parent
);
834 ((TextView
) v
).setTextColor(getResources().getColorStateList(
835 android
.R
.color
.white
));
839 public View
getDropDownView(int position
, View convertView
,
841 View v
= super.getDropDownView(position
, convertView
, parent
);
843 ((TextView
) v
).setTextColor(getResources().getColorStateList(
844 android
.R
.color
.white
));
851 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
854 * {@link BroadcastReceiver} to enable syncing feedback in UI
857 public void onReceive(Context context
, Intent intent
) {
858 boolean inProgress
= intent
.getBooleanExtra(
859 FileSyncService
.IN_PROGRESS
, false
);
860 String accountName
= intent
861 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
863 Log
.d("FileDisplay", "sync of account " + accountName
864 + " is in_progress: " + inProgress
);
866 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
868 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
870 boolean fillBlankRoot
= false
;
871 if (mCurrentDir
== null
) {
872 mCurrentDir
= mStorageManager
.getFileByPath("/");
873 fillBlankRoot
= (mCurrentDir
!= null
);
876 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
879 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
880 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
881 .findFragmentById(R
.id
.fileList
);
882 if (fileListFragment
!= null
) {
883 fileListFragment
.listDirectory(mCurrentDir
);
887 setSupportProgressBarIndeterminateVisibility(inProgress
);
888 removeStickyBroadcast(intent
);
892 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.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
) && (uploadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
915 if (sameAccount
&& isDescendant
) {
916 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
917 if (fileListFragment
!= null
) {
918 fileListFragment
.listDirectory();
927 * Once the file download has finished -> update view
929 private class DownloadFinishReceiver
extends BroadcastReceiver
{
931 public void onReceive(Context context
, Intent intent
) {
932 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
933 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
934 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
935 boolean isDescendant
= (mCurrentDir
!= null
) && (downloadedRemotePath
!= null
) && (downloadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
936 if (sameAccount
&& isDescendant
) {
937 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
938 if (fileListFragment
!= null
) {
939 fileListFragment
.listDirectory();
952 public DataStorageManager
getStorageManager() {
953 return mStorageManager
;
961 public void onDirectoryClick(OCFile directory
) {
962 pushDirname(directory
);
963 ActionBar actionBar
= getSupportActionBar();
964 actionBar
.setDisplayHomeAsUpEnabled(true
);
967 // Resets the FileDetailsFragment on Tablets so that it always displays
968 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
969 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
970 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
971 transaction
.remove(fileDetails
);
972 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
973 transaction
.commit();
983 public void onFileClick(OCFile file
) {
985 // If we are on a large device -> update fragment
987 // 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'
988 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
989 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
990 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
991 transaction
.commit();
993 } else { // small or medium screen device -> new Activity
994 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
995 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
996 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
997 startActivity(showDetailsIntent
);
1006 public OCFile
getInitialDirectory() {
1015 public void onFileStateChanged() {
1016 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
1017 if (fileListFragment
!= null
) {
1018 fileListFragment
.listDirectory();
1027 public FileDownloaderBinder
getFileDownloaderBinder() {
1028 return mDownloaderBinder
;
1036 public FileUploaderBinder
getFileUploaderBinder() {
1037 return mUploaderBinder
;
1041 /** Defines callbacks for service binding, passed to bindService() */
1042 private class ListServiceConnection
implements ServiceConnection
{
1045 public void onServiceConnected(ComponentName component
, IBinder service
) {
1046 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1047 Log
.d(TAG
, "Download service connected");
1048 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1049 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1050 Log
.d(TAG
, "Upload service connected");
1051 mUploaderBinder
= (FileUploaderBinder
) service
;
1055 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1056 if (mFileList
!= null
)
1057 mFileList
.listDirectory();
1059 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1060 if (fragment
!= null
)
1061 fragment
.updateFileDetails(false
);
1066 public void onServiceDisconnected(ComponentName component
) {
1067 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1068 Log
.d(TAG
, "Download service disconnected");
1069 mDownloaderBinder
= null
;
1070 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1071 Log
.d(TAG
, "Upload service disconnected");
1072 mUploaderBinder
= null
;
1080 * Launch an intent to request the PIN code to the user before letting him use the app
1082 private void requestPinCode() {
1083 boolean pinStart
= false
;
1084 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1085 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1087 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1088 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1095 public void onSavedCertificate() {
1096 startSynchronization();
1101 public void onFailedSavingCertificate() {
1102 showDialog(DIALOG_CERT_NOT_SAVED
);
1107 * Updates the view associated to the activity after the finish of some operation over files
1108 * in the current account.
1110 * @param operation Removal operation performed.
1111 * @param result Result of the removal.
1114 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1115 if (operation
instanceof RemoveFileOperation
) {
1116 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1118 } else if (operation
instanceof RenameFileOperation
) {
1119 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1121 } else if (operation
instanceof SynchronizeFileOperation
) {
1122 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1128 * Updates the view associated to the activity after the finish of an operation trying to remove a
1131 * @param operation Removal operation performed.
1132 * @param result Result of the removal.
1134 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1135 dismissDialog(DIALOG_SHORT_WAIT
);
1136 if (result
.isSuccess()) {
1137 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1139 OCFile removedFile
= operation
.getFile();
1141 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1142 if (details
!= null
&& removedFile
.equals(details
.getDisplayedFile()) ) {
1143 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
1144 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1145 transaction
.commit();
1148 if (mStorageManager
.getFileById(removedFile
.getParentId()).equals(mCurrentDir
)) {
1149 mFileList
.listDirectory();
1153 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1155 if (result
.isSslRecoverableException()) {
1156 mLastSslUntrustedServerResult
= result
;
1157 showDialog(DIALOG_SSL_VALIDATOR
);
1163 * Updates the view associated to the activity after the finish of an operation trying to rename a
1166 * @param operation Renaming operation performed.
1167 * @param result Result of the renaming.
1169 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1170 dismissDialog(DIALOG_SHORT_WAIT
);
1171 OCFile renamedFile
= operation
.getFile();
1172 if (result
.isSuccess()) {
1174 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1175 if (details
!= null
&& renamedFile
.equals(details
.getDisplayedFile()) ) {
1176 details
.updateFileDetails(renamedFile
, AccountUtils
.getCurrentOwnCloudAccount(this));
1179 if (mStorageManager
.getFileById(renamedFile
.getParentId()).equals(mCurrentDir
)) {
1180 mFileList
.listDirectory();
1184 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1185 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1187 // TODO throw again the new rename dialog
1189 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1191 if (result
.isSslRecoverableException()) {
1192 mLastSslUntrustedServerResult
= result
;
1193 showDialog(DIALOG_SSL_VALIDATOR
);
1200 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1201 dismissDialog(DIALOG_SHORT_WAIT
);
1202 OCFile syncedFile
= operation
.getLocalFile();
1203 if (!result
.isSuccess()) {
1204 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1205 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1206 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1207 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
1211 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1216 if (operation
.transferWasRequested()) {
1217 mFileList
.listDirectory();
1218 onTransferStateChanged(syncedFile
, true
, true
);
1221 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1232 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1233 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1234 if (fileListFragment != null) {
1235 fileListFragment.listDirectory();
1238 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1239 if (details
!= null
&& file
.equals(details
.getDisplayedFile()) ) {
1240 if (downloading
|| uploading
) {
1241 details
.updateFileDetails(file
, AccountUtils
.getCurrentOwnCloudAccount(this));
1243 details
.updateFileDetails(downloading
|| uploading
);