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
.operations
.CreateFolderOperation
;
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
;
93 * Displays, what files the user has available in his ownCloud.
95 * @author Bartek Przybylski
99 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
100 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, OnRemoteOperationListener
{
102 private ArrayAdapter
<String
> mDirectories
;
103 private OCFile mCurrentDir
= null
;
104 private OCFile mCurrentFile
= null
;
106 private DataStorageManager mStorageManager
;
107 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
108 private UploadFinishReceiver mUploadFinishReceiver
;
109 private DownloadFinishReceiver mDownloadFinishReceiver
;
110 private FileDownloaderBinder mDownloaderBinder
= null
;
111 private FileUploaderBinder mUploaderBinder
= null
;
112 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
113 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
115 private OCFileListFragment mFileList
;
117 private boolean mDualPane
;
118 private Handler mHandler
;
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 mHandler
= new Handler();
143 /// Load of parameters from received intent
144 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
145 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
147 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
149 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
150 if(savedInstanceState
!= null
) {
151 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
152 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
155 if (!AccountUtils
.accountsAreSetup(this)) {
156 /// no account available: FORCE ACCOUNT CREATION
157 mStorageManager
= null
;
158 createFirstAccount();
160 } else { /// at least an account is available
162 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
166 mUploadConnection
= new ListServiceConnection();
167 mDownloadConnection
= new ListServiceConnection();
168 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
169 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
171 // PIN CODE request ; best location is to decide, let's try this first
172 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
177 Intent observer_intent
= new Intent(this, FileObserverService
.class);
178 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
179 startService(observer_intent
);
183 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
185 // Drop-down navigation
186 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
187 OCFile currFile
= mCurrentDir
;
188 while(currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
189 mDirectories
.add(currFile
.getFileName());
190 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
192 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
194 // Inflate and set the layout view
195 setContentView(R
.layout
.files
);
196 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
197 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
199 initFileDetailsInDualPane();
203 ActionBar actionBar
= getSupportActionBar();
204 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
205 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
206 actionBar
.setDisplayShowTitleEnabled(false
);
207 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
208 actionBar
.setListNavigationCallbacks(mDirectories
, this);
209 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
211 Log
.d(getClass().toString(), "onCreate() end");
216 * Launches the account creation activity. To use when no ownCloud account is available
218 private void createFirstAccount() {
219 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
220 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTHORITY
});
221 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
226 * Load of state dependent of the existence of an ownCloud account
228 private void initDataFromCurrentAccount() {
229 /// Storage manager initialization - access to local database
230 mStorageManager
= new FileDataStorageManager(
231 AccountUtils
.getCurrentOwnCloudAccount(this),
232 getContentResolver());
234 /// Check if mCurrentDir is a directory
235 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
236 mCurrentFile
= mCurrentDir
;
237 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
240 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
241 if (mCurrentDir
!= null
) {
242 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
244 if (mCurrentFile
!= null
) {
245 if (mCurrentFile
.fileExists()) {
246 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
247 } // 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
250 /// Default to root if mCurrentDir was not found
251 if (mCurrentDir
== null
) {
252 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
257 private void initFileDetailsInDualPane() {
258 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
259 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
260 if (mCurrentFile
!= null
) {
261 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
); // empty FileDetailFragment
264 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
266 transaction
.commit();
272 public void onDestroy() {
274 if (mDownloadConnection
!= null
)
275 unbindService(mDownloadConnection
);
276 if (mUploadConnection
!= null
)
277 unbindService(mUploadConnection
);
282 public boolean onCreateOptionsMenu(Menu menu
) {
283 MenuInflater inflater
= getSherlock().getMenuInflater();
284 inflater
.inflate(R
.menu
.menu
, menu
);
286 patchHiddenAccents(menu
);
292 * 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>
294 * @param menu Menu to patch
296 private void patchHiddenAccents(Menu menu
) {
297 for (int i
= 0; i
< mMenuIdentifiersToPatch
.length
; i
++) {
298 MenuItem aboutItem
= menu
.findItem(mMenuIdentifiersToPatch
[i
]);
299 if (aboutItem
!= null
&& aboutItem
.getIcon() instanceof BitmapDrawable
) {
300 // Clip off the bottom three (density independent) pixels of transparent padding
301 Bitmap original
= ((BitmapDrawable
) aboutItem
.getIcon()).getBitmap();
302 float scale
= getResources().getDisplayMetrics().density
;
303 int clippedHeight
= (int) (original
.getHeight() - (3 * scale
));
304 Bitmap scaled
= Bitmap
.createBitmap(original
, 0, 0, original
.getWidth(), clippedHeight
);
305 aboutItem
.setIcon(new BitmapDrawable(getResources(), scaled
));
312 public boolean onOptionsItemSelected(MenuItem item
) {
313 boolean retval
= true
;
314 switch (item
.getItemId()) {
315 case R
.id
.createDirectoryItem
: {
316 showDialog(DIALOG_CREATE_DIR
);
319 case R
.id
.startSync
: {
320 startSynchronization();
323 case R
.id
.action_upload
: {
324 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
327 case R
.id
.action_settings
: {
328 Intent settingsIntent
= new Intent(this, Preferences
.class);
329 startActivity(settingsIntent
);
332 case R
.id
.about_app
: {
333 showDialog(DIALOG_ABOUT_APP
);
336 case android
.R
.id
.home
: {
337 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
343 retval
= super.onOptionsItemSelected(item
);
348 private void startSynchronization() {
349 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTHORITY
); // cancel the current synchronizations of any ownCloud account
350 Bundle bundle
= new Bundle();
351 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
352 ContentResolver
.requestSync(
353 AccountUtils
.getCurrentOwnCloudAccount(this),
354 AccountAuthenticator
.AUTHORITY
, bundle
);
359 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
360 int i
= itemPosition
;
364 // the next operation triggers a new call to this method, but it's necessary to
365 // ensure that the name exposed in the action bar is the current directory when the
366 // user selected it in the navigation list
367 if (itemPosition
!= 0)
368 getSupportActionBar().setSelectedNavigationItem(0);
373 * Called, when the user selected something for uploading
375 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
377 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
378 requestSimpleUpload(data
, resultCode
);
380 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
381 requestMultipleUpload(data
, resultCode
);
386 private void requestMultipleUpload(Intent data
, int resultCode
) {
387 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
388 if (filePaths
!= null
) {
389 String
[] remotePaths
= new String
[filePaths
.length
];
390 String remotePathBase
= "";
391 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
392 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
394 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
395 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
396 for (int j
= 0; j
< remotePaths
.length
; j
++) {
397 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
400 Intent i
= new Intent(this, FileUploader
.class);
401 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
402 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
403 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
404 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
405 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
406 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
410 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
411 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
418 private void requestSimpleUpload(Intent data
, int resultCode
) {
419 String filepath
= null
;
421 Uri selectedImageUri
= data
.getData();
423 String filemanagerstring
= selectedImageUri
.getPath();
424 String selectedImagePath
= getPath(selectedImageUri
);
426 if (selectedImagePath
!= null
)
427 filepath
= selectedImagePath
;
429 filepath
= filemanagerstring
;
431 } catch (Exception e
) {
432 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
436 if (filepath
== null
) {
437 Log
.e("FileDisplay", "Couldnt resolve path to file");
438 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
444 Intent i
= new Intent(this, FileUploader
.class);
445 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
446 AccountUtils
.getCurrentOwnCloudAccount(this));
447 String remotepath
= new String();
448 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
449 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
451 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
452 remotepath
+= OCFile
.PATH_SEPARATOR
;
453 remotepath
+= new File(filepath
).getName();
455 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
456 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
457 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
458 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
459 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
465 public void onBackPressed() {
466 if (mDirectories
.getCount() <= 1) {
471 mFileList
.onNavigateUp();
472 mCurrentDir
= mFileList
.getCurrentFile();
475 // Resets the FileDetailsFragment on Tablets so that it always displays
476 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
477 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
478 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
479 transaction
.remove(fileDetails
);
480 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
481 transaction
.commit();
485 if(mCurrentDir
.getParentId() == 0){
486 ActionBar actionBar
= getSupportActionBar();
487 actionBar
.setDisplayHomeAsUpEnabled(false
);
492 protected void onSaveInstanceState(Bundle outState
) {
493 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
494 Log
.d(getClass().toString(), "onSaveInstanceState() start");
495 super.onSaveInstanceState(outState
);
496 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
498 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
499 if (fragment
!= null
) {
500 OCFile file
= fragment
.getDisplayedFile();
502 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
506 Log
.d(getClass().toString(), "onSaveInstanceState() end");
510 protected void onResume() {
511 Log
.d(getClass().toString(), "onResume() start");
514 if (AccountUtils
.accountsAreSetup(this)) {
516 if (mStorageManager
== null
) {
517 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
518 initDataFromCurrentAccount();
520 initFileDetailsInDualPane();
524 // Listen for sync messages
525 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
526 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
527 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
529 // Listen for upload messages
530 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
531 mUploadFinishReceiver
= new UploadFinishReceiver();
532 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
534 // Listen for download messages
535 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
536 mDownloadFinishReceiver
= new DownloadFinishReceiver();
537 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
539 // List current directory
540 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
544 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
545 showDialog(DIALOG_SETUP_ACCOUNT
);
548 Log
.d(getClass().toString(), "onResume() end");
553 protected void onPause() {
554 Log
.d(getClass().toString(), "onPause() start");
556 if (mSyncBroadcastReceiver
!= null
) {
557 unregisterReceiver(mSyncBroadcastReceiver
);
558 mSyncBroadcastReceiver
= null
;
560 if (mUploadFinishReceiver
!= null
) {
561 unregisterReceiver(mUploadFinishReceiver
);
562 mUploadFinishReceiver
= null
;
564 if (mDownloadFinishReceiver
!= null
) {
565 unregisterReceiver(mDownloadFinishReceiver
);
566 mDownloadFinishReceiver
= null
;
568 if (!AccountUtils
.accountsAreSetup(this)) {
569 dismissDialog(DIALOG_SETUP_ACCOUNT
);
572 Log
.d(getClass().toString(), "onPause() end");
577 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
578 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
579 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
585 protected Dialog
onCreateDialog(int id
) {
586 Dialog dialog
= null
;
587 AlertDialog
.Builder builder
;
589 case DIALOG_SETUP_ACCOUNT
: {
590 builder
= new AlertDialog
.Builder(this);
591 builder
.setTitle(R
.string
.main_tit_accsetup
);
592 builder
.setMessage(R
.string
.main_wrn_accsetup
);
593 builder
.setCancelable(false
);
594 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
595 public void onClick(DialogInterface dialog
, int which
) {
596 createFirstAccount();
600 String message
= String
.format(getString(R
.string
.common_exit
), getString(R
.string
.app_name
));
601 builder
.setNegativeButton(message
, new OnClickListener() {
602 public void onClick(DialogInterface dialog
, int which
) {
607 //builder.setNegativeButton(android.R.string.cancel, this);
608 dialog
= builder
.create();
611 case DIALOG_ABOUT_APP
: {
612 builder
= new AlertDialog
.Builder(this);
613 builder
.setTitle(getString(R
.string
.about_title
));
616 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
617 builder
.setMessage(String
.format(getString(R
.string
.about_message
), getString(R
.string
.app_name
), pkg
.versionName
));
618 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
619 dialog
= builder
.create();
620 } catch (NameNotFoundException e
) {
623 Log
.e(TAG
, "Error while showing about dialog", e
);
627 case DIALOG_CREATE_DIR
: {
628 builder
= new Builder(this);
629 final EditText dirNameInput
= new EditText(getBaseContext());
630 builder
.setView(dirNameInput
);
631 builder
.setTitle(R
.string
.uploader_info_dirname
);
632 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
633 dirNameInput
.setTextColor(typed_color
);
634 builder
.setPositiveButton(android
.R
.string
.ok
,
635 new OnClickListener() {
636 public void onClick(DialogInterface dialog
, int which
) {
637 String directoryName
= dirNameInput
.getText().toString();
638 if (directoryName
.trim().length() == 0) {
643 // Figure out the path where the dir needs to be created
645 if (mCurrentDir
== null
) {
646 // this is just a patch; we should ensure that mCurrentDir never is null
647 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
648 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
649 mStorageManager
.saveFile(file
);
651 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
653 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
656 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
657 RemoteOperation operation
= new CreateFolderOperation(path
, mCurrentDir
.getFileId(), mStorageManager
);
658 operation
.execute( AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this),
659 FileDisplayActivity
.this,
660 FileDisplayActivity
.this,
662 FileDisplayActivity
.this);
666 showDialog(DIALOG_SHORT_WAIT
);
669 builder
.setNegativeButton(R
.string
.common_cancel
,
670 new OnClickListener() {
671 public void onClick(DialogInterface dialog
, int which
) {
675 dialog
= builder
.create();
678 case DIALOG_SHORT_WAIT
: {
679 ProgressDialog working_dialog
= new ProgressDialog(this);
680 working_dialog
.setMessage(getResources().getString(
681 R
.string
.wait_a_moment
));
682 working_dialog
.setIndeterminate(true
);
683 working_dialog
.setCancelable(false
);
684 dialog
= working_dialog
;
687 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
688 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
689 getString(R
.string
.actionbar_upload_from_apps
) };
690 builder
= new AlertDialog
.Builder(this);
691 builder
.setTitle(R
.string
.actionbar_upload
);
692 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
693 public void onClick(DialogInterface dialog
, int item
) {
696 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
697 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this));
698 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
700 // TODO create and handle new fragment LocalFileListFragment
702 } else if (item
== 1) {
703 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
704 action
= action
.setType("*/*")
705 .addCategory(Intent
.CATEGORY_OPENABLE
);
706 startActivityForResult(
707 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
708 ACTION_SELECT_CONTENT_FROM_APPS
);
712 dialog
= builder
.create();
715 case DIALOG_SSL_VALIDATOR
: {
716 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
719 case DIALOG_CERT_NOT_SAVED
: {
720 builder
= new AlertDialog
.Builder(this);
721 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
722 builder
.setCancelable(false
);
723 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
725 public void onClick(DialogInterface dialog
, int which
) {
729 dialog
= builder
.create();
741 * Translates a content URI of an image to a physical path
743 * @param uri The URI to resolve
744 * @return The path to the image or null if it could not be found
746 public String
getPath(Uri uri
) {
747 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
748 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
749 if (cursor
!= null
) {
750 int column_index
= cursor
751 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
752 cursor
.moveToFirst();
753 return cursor
.getString(column_index
);
759 * Pushes a directory to the drop down list
760 * @param directory to push
761 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
763 public void pushDirname(OCFile directory
) {
764 if(!directory
.isDirectory()){
765 throw new IllegalArgumentException("Only directories may be pushed!");
767 mDirectories
.insert(directory
.getFileName(), 0);
768 mCurrentDir
= directory
;
772 * Pops a directory name from the drop down list
773 * @return True, unless the stack is empty
775 public boolean popDirname() {
776 mDirectories
.remove(mDirectories
.getItem(0));
777 return !mDirectories
.isEmpty();
781 // Custom array adapter to override text colors
782 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
784 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
788 public View
getView(int position
, View convertView
, ViewGroup parent
) {
789 View v
= super.getView(position
, convertView
, parent
);
791 ((TextView
) v
).setTextColor(getResources().getColorStateList(
792 android
.R
.color
.white
));
796 public View
getDropDownView(int position
, View convertView
,
798 View v
= super.getDropDownView(position
, convertView
, parent
);
800 ((TextView
) v
).setTextColor(getResources().getColorStateList(
801 android
.R
.color
.white
));
808 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
811 * {@link BroadcastReceiver} to enable syncing feedback in UI
814 public void onReceive(Context context
, Intent intent
) {
815 boolean inProgress
= intent
.getBooleanExtra(
816 FileSyncService
.IN_PROGRESS
, false
);
817 String accountName
= intent
818 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
820 Log
.d("FileDisplay", "sync of account " + accountName
821 + " is in_progress: " + inProgress
);
823 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
825 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
827 boolean fillBlankRoot
= false
;
828 if (mCurrentDir
== null
) {
829 mCurrentDir
= mStorageManager
.getFileByPath("/");
830 fillBlankRoot
= (mCurrentDir
!= null
);
833 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
836 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
837 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
838 .findFragmentById(R
.id
.fileList
);
839 if (fileListFragment
!= null
) {
840 fileListFragment
.listDirectory(mCurrentDir
);
844 setSupportProgressBarIndeterminateVisibility(inProgress
);
845 removeStickyBroadcast(intent
);
849 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncService
.SYNC_RESULT
);
850 if (synchResult
!= null
) {
851 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
852 mLastSslUntrustedServerResult
= synchResult
;
853 showDialog(DIALOG_SSL_VALIDATOR
);
860 private class UploadFinishReceiver
extends BroadcastReceiver
{
862 * Once the file upload has finished -> update view
863 * @author David A. Velasco
864 * {@link BroadcastReceiver} to enable upload feedback in UI
867 public void onReceive(Context context
, Intent intent
) {
868 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
869 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
870 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
871 boolean isDescendant
= (mCurrentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
872 if (sameAccount
&& isDescendant
) {
873 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
874 if (fileListFragment
!= null
) {
875 fileListFragment
.listDirectory();
884 * Once the file download has finished -> update view
886 private class DownloadFinishReceiver
extends BroadcastReceiver
{
888 public void onReceive(Context context
, Intent intent
) {
889 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
890 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
891 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
892 boolean isDescendant
= (mCurrentDir
!= null
) && (downloadedRemotePath
!= null
) && (downloadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
893 if (sameAccount
&& isDescendant
) {
894 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
895 if (fileListFragment
!= null
) {
896 fileListFragment
.listDirectory();
909 public DataStorageManager
getStorageManager() {
910 return mStorageManager
;
918 public void onDirectoryClick(OCFile directory
) {
919 pushDirname(directory
);
920 ActionBar actionBar
= getSupportActionBar();
921 actionBar
.setDisplayHomeAsUpEnabled(true
);
924 // Resets the FileDetailsFragment on Tablets so that it always displays
925 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
926 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
927 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
928 transaction
.remove(fileDetails
);
929 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
930 transaction
.commit();
940 public void onFileClick(OCFile file
) {
942 // If we are on a large device -> update fragment
944 // 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'
945 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
946 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
947 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
948 transaction
.commit();
950 } else { // small or medium screen device -> new Activity
951 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
952 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
953 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
954 startActivity(showDetailsIntent
);
963 public OCFile
getInitialDirectory() {
972 public void onFileStateChanged() {
973 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
974 if (fileListFragment
!= null
) {
975 fileListFragment
.listDirectory();
984 public FileDownloaderBinder
getFileDownloaderBinder() {
985 return mDownloaderBinder
;
993 public FileUploaderBinder
getFileUploaderBinder() {
994 return mUploaderBinder
;
998 /** Defines callbacks for service binding, passed to bindService() */
999 private class ListServiceConnection
implements ServiceConnection
{
1002 public void onServiceConnected(ComponentName component
, IBinder service
) {
1003 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1004 Log
.d(TAG
, "Download service connected");
1005 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1006 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1007 Log
.d(TAG
, "Upload service connected");
1008 mUploaderBinder
= (FileUploaderBinder
) service
;
1012 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1013 if (mFileList
!= null
)
1014 mFileList
.listDirectory();
1016 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1017 if (fragment
!= null
)
1018 fragment
.updateFileDetails(false
);
1023 public void onServiceDisconnected(ComponentName component
) {
1024 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1025 Log
.d(TAG
, "Download service disconnected");
1026 mDownloaderBinder
= null
;
1027 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1028 Log
.d(TAG
, "Upload service disconnected");
1029 mUploaderBinder
= null
;
1037 * Launch an intent to request the PIN code to the user before letting him use the app
1039 private void requestPinCode() {
1040 boolean pinStart
= false
;
1041 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1042 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1044 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1045 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1052 public void onSavedCertificate() {
1053 startSynchronization();
1058 public void onFailedSavingCertificate() {
1059 showDialog(DIALOG_CERT_NOT_SAVED
);
1064 * Updates the view associated to the activity after the finish of some operation over files
1065 * in the current account.
1067 * @param operation Removal operation performed.
1068 * @param result Result of the removal.
1071 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1072 if (operation
instanceof RemoveFileOperation
) {
1073 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1075 } else if (operation
instanceof RenameFileOperation
) {
1076 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1078 } else if (operation
instanceof SynchronizeFileOperation
) {
1079 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1081 } else if (operation
instanceof CreateFolderOperation
) {
1082 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1087 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1089 * @param operation Creation operation performed.
1090 * @param result Result of the creation.
1092 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1093 if (result
.isSuccess()) {
1094 dismissDialog(DIALOG_SHORT_WAIT
);
1095 mFileList
.listDirectory();
1098 dismissDialog(DIALOG_SHORT_WAIT
);
1100 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1103 } catch (NotFoundException e
) {
1104 Log
.e(TAG
, "Error while trying to show fail message " , e
);
1111 * Updates the view associated to the activity after the finish of an operation trying to remove a
1114 * @param operation Removal operation performed.
1115 * @param result Result of the removal.
1117 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1118 dismissDialog(DIALOG_SHORT_WAIT
);
1119 if (result
.isSuccess()) {
1120 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1122 OCFile removedFile
= operation
.getFile();
1124 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1125 if (details
!= null
&& removedFile
.equals(details
.getDisplayedFile()) ) {
1126 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
1127 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1128 transaction
.commit();
1131 if (mStorageManager
.getFileById(removedFile
.getParentId()).equals(mCurrentDir
)) {
1132 mFileList
.listDirectory();
1136 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1138 if (result
.isSslRecoverableException()) {
1139 mLastSslUntrustedServerResult
= result
;
1140 showDialog(DIALOG_SSL_VALIDATOR
);
1146 * Updates the view associated to the activity after the finish of an operation trying to rename a
1149 * @param operation Renaming operation performed.
1150 * @param result Result of the renaming.
1152 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1153 dismissDialog(DIALOG_SHORT_WAIT
);
1154 OCFile renamedFile
= operation
.getFile();
1155 if (result
.isSuccess()) {
1157 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1158 if (details
!= null
&& renamedFile
.equals(details
.getDisplayedFile()) ) {
1159 details
.updateFileDetails(renamedFile
, AccountUtils
.getCurrentOwnCloudAccount(this));
1162 if (mStorageManager
.getFileById(renamedFile
.getParentId()).equals(mCurrentDir
)) {
1163 mFileList
.listDirectory();
1167 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1168 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1170 // TODO throw again the new rename dialog
1172 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1174 if (result
.isSslRecoverableException()) {
1175 mLastSslUntrustedServerResult
= result
;
1176 showDialog(DIALOG_SSL_VALIDATOR
);
1183 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1184 dismissDialog(DIALOG_SHORT_WAIT
);
1185 OCFile syncedFile
= operation
.getLocalFile();
1186 if (!result
.isSuccess()) {
1187 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1188 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1189 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1190 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
1194 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1199 if (operation
.transferWasRequested()) {
1200 mFileList
.listDirectory();
1201 onTransferStateChanged(syncedFile
, true
, true
);
1204 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1215 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1216 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1217 if (fileListFragment != null) {
1218 fileListFragment.listDirectory();
1221 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1222 if (details
!= null
&& file
.equals(details
.getDisplayedFile()) ) {
1223 if (downloading
|| uploading
) {
1224 details
.updateFileDetails(file
, AccountUtils
.getCurrentOwnCloudAccount(this));
1226 details
.updateFileDetails(downloading
|| uploading
);