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
.AUTH_TOKEN_TYPE
});
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
.AUTH_TOKEN_TYPE
); // 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
.AUTH_TOKEN_TYPE
, 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,
665 showDialog(DIALOG_SHORT_WAIT
);
668 builder
.setNegativeButton(R
.string
.common_cancel
,
669 new OnClickListener() {
670 public void onClick(DialogInterface dialog
, int which
) {
674 dialog
= builder
.create();
677 case DIALOG_SHORT_WAIT
: {
678 ProgressDialog working_dialog
= new ProgressDialog(this);
679 working_dialog
.setMessage(getResources().getString(
680 R
.string
.wait_a_moment
));
681 working_dialog
.setIndeterminate(true
);
682 working_dialog
.setCancelable(false
);
683 dialog
= working_dialog
;
686 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
687 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
688 getString(R
.string
.actionbar_upload_from_apps
) };
689 builder
= new AlertDialog
.Builder(this);
690 builder
.setTitle(R
.string
.actionbar_upload
);
691 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
692 public void onClick(DialogInterface dialog
, int item
) {
695 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
696 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this));
697 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
699 // TODO create and handle new fragment LocalFileListFragment
701 } else if (item
== 1) {
702 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
703 action
= action
.setType("*/*")
704 .addCategory(Intent
.CATEGORY_OPENABLE
);
705 startActivityForResult(
706 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
707 ACTION_SELECT_CONTENT_FROM_APPS
);
711 dialog
= builder
.create();
714 case DIALOG_SSL_VALIDATOR
: {
715 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
718 case DIALOG_CERT_NOT_SAVED
: {
719 builder
= new AlertDialog
.Builder(this);
720 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
721 builder
.setCancelable(false
);
722 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
724 public void onClick(DialogInterface dialog
, int which
) {
728 dialog
= builder
.create();
740 * Translates a content URI of an image to a physical path
742 * @param uri The URI to resolve
743 * @return The path to the image or null if it could not be found
745 public String
getPath(Uri uri
) {
746 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
747 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
748 if (cursor
!= null
) {
749 int column_index
= cursor
750 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
751 cursor
.moveToFirst();
752 return cursor
.getString(column_index
);
758 * Pushes a directory to the drop down list
759 * @param directory to push
760 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
762 public void pushDirname(OCFile directory
) {
763 if(!directory
.isDirectory()){
764 throw new IllegalArgumentException("Only directories may be pushed!");
766 mDirectories
.insert(directory
.getFileName(), 0);
767 mCurrentDir
= directory
;
771 * Pops a directory name from the drop down list
772 * @return True, unless the stack is empty
774 public boolean popDirname() {
775 mDirectories
.remove(mDirectories
.getItem(0));
776 return !mDirectories
.isEmpty();
780 // Custom array adapter to override text colors
781 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
783 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
787 public View
getView(int position
, View convertView
, ViewGroup parent
) {
788 View v
= super.getView(position
, convertView
, parent
);
790 ((TextView
) v
).setTextColor(getResources().getColorStateList(
791 android
.R
.color
.white
));
795 public View
getDropDownView(int position
, View convertView
,
797 View v
= super.getDropDownView(position
, convertView
, parent
);
799 ((TextView
) v
).setTextColor(getResources().getColorStateList(
800 android
.R
.color
.white
));
807 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
810 * {@link BroadcastReceiver} to enable syncing feedback in UI
813 public void onReceive(Context context
, Intent intent
) {
814 boolean inProgress
= intent
.getBooleanExtra(
815 FileSyncService
.IN_PROGRESS
, false
);
816 String accountName
= intent
817 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
819 Log
.d("FileDisplay", "sync of account " + accountName
820 + " is in_progress: " + inProgress
);
822 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
824 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
826 boolean fillBlankRoot
= false
;
827 if (mCurrentDir
== null
) {
828 mCurrentDir
= mStorageManager
.getFileByPath("/");
829 fillBlankRoot
= (mCurrentDir
!= null
);
832 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
835 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
836 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
837 .findFragmentById(R
.id
.fileList
);
838 if (fileListFragment
!= null
) {
839 fileListFragment
.listDirectory(mCurrentDir
);
843 setSupportProgressBarIndeterminateVisibility(inProgress
);
844 removeStickyBroadcast(intent
);
848 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncService
.SYNC_RESULT
);
849 if (synchResult
!= null
) {
850 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
851 mLastSslUntrustedServerResult
= synchResult
;
852 showDialog(DIALOG_SSL_VALIDATOR
);
859 private class UploadFinishReceiver
extends BroadcastReceiver
{
861 * Once the file upload has finished -> update view
862 * @author David A. Velasco
863 * {@link BroadcastReceiver} to enable upload feedback in UI
866 public void onReceive(Context context
, Intent intent
) {
867 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
868 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
869 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
870 boolean isDescendant
= (mCurrentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
871 if (sameAccount
&& isDescendant
) {
872 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
873 if (fileListFragment
!= null
) {
874 fileListFragment
.listDirectory();
883 * Once the file download has finished -> update view
885 private class DownloadFinishReceiver
extends BroadcastReceiver
{
887 public void onReceive(Context context
, Intent intent
) {
888 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
889 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
890 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
891 boolean isDescendant
= (mCurrentDir
!= null
) && (downloadedRemotePath
!= null
) && (downloadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
892 if (sameAccount
&& isDescendant
) {
893 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
894 if (fileListFragment
!= null
) {
895 fileListFragment
.listDirectory();
908 public DataStorageManager
getStorageManager() {
909 return mStorageManager
;
917 public void onDirectoryClick(OCFile directory
) {
918 pushDirname(directory
);
919 ActionBar actionBar
= getSupportActionBar();
920 actionBar
.setDisplayHomeAsUpEnabled(true
);
923 // Resets the FileDetailsFragment on Tablets so that it always displays
924 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
925 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
926 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
927 transaction
.remove(fileDetails
);
928 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
929 transaction
.commit();
939 public void onFileClick(OCFile file
) {
941 // If we are on a large device -> update fragment
943 // 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'
944 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
945 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
946 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
947 transaction
.commit();
949 } else { // small or medium screen device -> new Activity
950 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
951 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
952 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
953 startActivity(showDetailsIntent
);
962 public OCFile
getInitialDirectory() {
971 public void onFileStateChanged() {
972 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
973 if (fileListFragment
!= null
) {
974 fileListFragment
.listDirectory();
983 public FileDownloaderBinder
getFileDownloaderBinder() {
984 return mDownloaderBinder
;
992 public FileUploaderBinder
getFileUploaderBinder() {
993 return mUploaderBinder
;
997 /** Defines callbacks for service binding, passed to bindService() */
998 private class ListServiceConnection
implements ServiceConnection
{
1001 public void onServiceConnected(ComponentName component
, IBinder service
) {
1002 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1003 Log
.d(TAG
, "Download service connected");
1004 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1005 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1006 Log
.d(TAG
, "Upload service connected");
1007 mUploaderBinder
= (FileUploaderBinder
) service
;
1011 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1012 if (mFileList
!= null
)
1013 mFileList
.listDirectory();
1015 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1016 if (fragment
!= null
)
1017 fragment
.updateFileDetails(false
);
1022 public void onServiceDisconnected(ComponentName component
) {
1023 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1024 Log
.d(TAG
, "Download service disconnected");
1025 mDownloaderBinder
= null
;
1026 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1027 Log
.d(TAG
, "Upload service disconnected");
1028 mUploaderBinder
= null
;
1036 * Launch an intent to request the PIN code to the user before letting him use the app
1038 private void requestPinCode() {
1039 boolean pinStart
= false
;
1040 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1041 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1043 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1044 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1051 public void onSavedCertificate() {
1052 startSynchronization();
1057 public void onFailedSavingCertificate() {
1058 showDialog(DIALOG_CERT_NOT_SAVED
);
1063 * Updates the view associated to the activity after the finish of some operation over files
1064 * in the current account.
1066 * @param operation Removal operation performed.
1067 * @param result Result of the removal.
1070 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1071 if (operation
instanceof RemoveFileOperation
) {
1072 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1074 } else if (operation
instanceof RenameFileOperation
) {
1075 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1077 } else if (operation
instanceof SynchronizeFileOperation
) {
1078 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1080 } else if (operation
instanceof CreateFolderOperation
) {
1081 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1086 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1088 * @param operation Creation operation performed.
1089 * @param result Result of the creation.
1091 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1092 if (result
.isSuccess()) {
1093 dismissDialog(DIALOG_SHORT_WAIT
);
1094 mFileList
.listDirectory();
1097 dismissDialog(DIALOG_SHORT_WAIT
);
1099 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1102 } catch (NotFoundException e
) {
1103 Log
.e(TAG
, "Error while trying to show fail message " , e
);
1110 * Updates the view associated to the activity after the finish of an operation trying to remove a
1113 * @param operation Removal operation performed.
1114 * @param result Result of the removal.
1116 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1117 dismissDialog(DIALOG_SHORT_WAIT
);
1118 if (result
.isSuccess()) {
1119 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1121 OCFile removedFile
= operation
.getFile();
1123 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1124 if (details
!= null
&& removedFile
.equals(details
.getDisplayedFile()) ) {
1125 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
1126 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1127 transaction
.commit();
1130 if (mStorageManager
.getFileById(removedFile
.getParentId()).equals(mCurrentDir
)) {
1131 mFileList
.listDirectory();
1135 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1137 if (result
.isSslRecoverableException()) {
1138 mLastSslUntrustedServerResult
= result
;
1139 showDialog(DIALOG_SSL_VALIDATOR
);
1145 * Updates the view associated to the activity after the finish of an operation trying to rename a
1148 * @param operation Renaming operation performed.
1149 * @param result Result of the renaming.
1151 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1152 dismissDialog(DIALOG_SHORT_WAIT
);
1153 OCFile renamedFile
= operation
.getFile();
1154 if (result
.isSuccess()) {
1156 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1157 if (details
!= null
&& renamedFile
.equals(details
.getDisplayedFile()) ) {
1158 details
.updateFileDetails(renamedFile
, AccountUtils
.getCurrentOwnCloudAccount(this));
1161 if (mStorageManager
.getFileById(renamedFile
.getParentId()).equals(mCurrentDir
)) {
1162 mFileList
.listDirectory();
1166 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1167 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1169 // TODO throw again the new rename dialog
1171 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1173 if (result
.isSslRecoverableException()) {
1174 mLastSslUntrustedServerResult
= result
;
1175 showDialog(DIALOG_SSL_VALIDATOR
);
1182 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1183 dismissDialog(DIALOG_SHORT_WAIT
);
1184 OCFile syncedFile
= operation
.getLocalFile();
1185 if (!result
.isSuccess()) {
1186 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1187 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1188 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1189 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
1193 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1198 if (operation
.transferWasRequested()) {
1199 mFileList
.listDirectory();
1200 onTransferStateChanged(syncedFile
, true
, true
);
1203 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1214 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1215 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1216 if (fileListFragment != null) {
1217 fileListFragment.listDirectory();
1220 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1221 if (details
!= null
&& file
.equals(details
.getDisplayedFile()) ) {
1222 if (downloading
|| uploading
) {
1223 details
.updateFileDetails(file
, AccountUtils
.getCurrentOwnCloudAccount(this));
1225 details
.updateFileDetails(downloading
|| uploading
);