1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 package com
.owncloud
.android
.ui
.activity
;
24 import android
.accounts
.Account
;
25 import android
.app
.AlertDialog
;
26 import android
.app
.AlertDialog
.Builder
;
27 import android
.app
.Dialog
;
28 import android
.app
.ProgressDialog
;
29 import android
.content
.BroadcastReceiver
;
30 import android
.content
.ComponentName
;
31 import android
.content
.ContentResolver
;
32 import android
.content
.Context
;
33 import android
.content
.DialogInterface
;
34 import android
.content
.DialogInterface
.OnClickListener
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SharedPreferences
.Editor
;
40 import android
.content
.pm
.PackageInfo
;
41 import android
.content
.pm
.PackageManager
.NameNotFoundException
;
42 import android
.content
.res
.Resources
.NotFoundException
;
43 import android
.database
.Cursor
;
44 import android
.graphics
.Bitmap
;
45 import android
.graphics
.drawable
.BitmapDrawable
;
46 import android
.net
.Uri
;
47 import android
.os
.Bundle
;
48 import android
.os
.Handler
;
49 import android
.os
.IBinder
;
50 import android
.preference
.PreferenceManager
;
51 import android
.provider
.MediaStore
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.util
.Log
;
54 import android
.view
.View
;
55 import android
.view
.ViewGroup
;
56 import android
.widget
.ArrayAdapter
;
57 import android
.widget
.EditText
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.ActionBar
;
62 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
63 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
64 import com
.actionbarsherlock
.view
.Menu
;
65 import com
.actionbarsherlock
.view
.MenuInflater
;
66 import com
.actionbarsherlock
.view
.MenuItem
;
67 import com
.actionbarsherlock
.view
.Window
;
68 import com
.owncloud
.android
.AccountUtils
;
69 import com
.owncloud
.android
.R
;
70 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
71 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
72 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
73 import com
.owncloud
.android
.datamodel
.OCFile
;
74 import com
.owncloud
.android
.files
.services
.FileDownloader
;
75 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
76 import com
.owncloud
.android
.files
.services
.FileObserverService
;
77 import com
.owncloud
.android
.files
.services
.FileUploader
;
78 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
79 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
80 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
81 import com
.owncloud
.android
.operations
.RemoteOperation
;
82 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
83 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
88 import com
.owncloud
.android
.ui
.dialog
.ChangelogDialog
;
89 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
91 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
92 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
94 import eu
.alefzero
.webdav
.WebdavClient
;
97 * Displays, what files the user has available in his ownCloud.
99 * @author Bartek Przybylski
103 public class FileDisplayActivity
extends SherlockFragmentActivity
implements OCFileListFragment
.ContainerActivity
,
104 FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, OnRemoteOperationListener
{
106 private ArrayAdapter
<String
> mDirectories
;
107 private OCFile mCurrentDir
= null
;
108 private OCFile mCurrentFile
= null
;
110 private DataStorageManager mStorageManager
;
111 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
112 private UploadFinishReceiver mUploadFinishReceiver
;
113 private DownloadFinishReceiver mDownloadFinishReceiver
;
114 private FileDownloaderBinder mDownloaderBinder
= null
;
115 private FileUploaderBinder mUploaderBinder
= null
;
116 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
117 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
119 private OCFileListFragment mFileList
;
121 private boolean mDualPane
;
123 private static final int DIALOG_SETUP_ACCOUNT
= 0;
124 private static final int DIALOG_CREATE_DIR
= 1;
125 public static final int DIALOG_SHORT_WAIT
= 3;
126 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
127 private static final int DIALOG_SSL_VALIDATOR
= 5;
128 private static final int DIALOG_CERT_NOT_SAVED
= 6;
129 private static final String DIALOG_CHANGELOG_TAG
= "DIALOG_CHANGELOG";
132 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
133 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
134 private static final int ACTION_SELECT_FAILED_INSTANT_UPLOAD
= 2;
136 private static final String TAG
= "FileDisplayActivity";
140 public void onCreate(Bundle savedInstanceState
) {
141 Log
.d(getClass().toString(), "onCreate() start");
142 super.onCreate(savedInstanceState
);
144 /// Load of parameters from received intent
145 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
146 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
148 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
150 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
151 if(savedInstanceState
!= null
) {
152 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
153 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
156 if (!AccountUtils
.accountsAreSetup(this)) {
157 /// no account available: FORCE ACCOUNT CREATION
158 mStorageManager
= null
;
159 createFirstAccount();
161 } else { // / at least an account is available
163 initDataFromCurrentAccount(); // it checks mCurrentDir and
164 // mCurrentFile with the current
169 mUploadConnection
= new ListServiceConnection();
170 mDownloadConnection
= new ListServiceConnection();
171 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
172 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
174 // PIN CODE request ; best location is to decide, let's try this first
175 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
180 Intent observer_intent
= new Intent(this, FileObserverService
.class);
181 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
182 startService(observer_intent
);
186 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
188 // Drop-down navigation
189 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
190 OCFile currFile
= mCurrentDir
;
191 while (currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
192 mDirectories
.add(currFile
.getFileName());
193 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
195 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
197 // Inflate and set the layout view
198 setContentView(R
.layout
.files
);
199 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
200 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
202 initFileDetailsInDualPane();
206 ActionBar actionBar
= getSupportActionBar();
207 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
208 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
209 actionBar
.setDisplayShowTitleEnabled(false
);
210 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
211 actionBar
.setListNavigationCallbacks(mDirectories
, this);
212 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
215 // show changelog, if needed
218 Log
.d(getClass().toString(), "onCreate() end");
223 * Shows a dialog with the change log of the current version after each app update
225 * TODO make it permanent; by now, only to advice the workaround app for 4.1.x
227 private void showChangeLog() {
228 if (android
.os
.Build
.VERSION
.SDK_INT
== android
.os
.Build
.VERSION_CODES
.JELLY_BEAN
) {
229 final String KEY_VERSION
= "version";
230 SharedPreferences sharedPref
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
231 int currentVersionNumber
= 0;
232 int savedVersionNumber
= sharedPref
.getInt(KEY_VERSION
, 0);
234 PackageInfo pi
= getPackageManager().getPackageInfo(getPackageName(), 0);
235 currentVersionNumber
= pi
.versionCode
;
236 } catch (Exception e
) {}
238 if (currentVersionNumber
> savedVersionNumber
) {
239 ChangelogDialog
.newInstance(true
).show(getSupportFragmentManager(), DIALOG_CHANGELOG_TAG
);
240 Editor editor
= sharedPref
.edit();
241 editor
.putInt(KEY_VERSION
, currentVersionNumber
);
249 * Launches the account creation activity. To use when no ownCloud account is available
251 private void createFirstAccount() {
252 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
253 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
254 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
259 * Load of state dependent of the existence of an ownCloud account
261 private void initDataFromCurrentAccount() {
262 /// Storage manager initialization - access to local database
263 mStorageManager
= new FileDataStorageManager(
264 AccountUtils
.getCurrentOwnCloudAccount(this),
265 getContentResolver());
267 /// Check if mCurrentDir is a directory
268 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
269 mCurrentFile
= mCurrentDir
;
270 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
273 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
274 if (mCurrentDir
!= null
) {
275 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
277 if (mCurrentFile
!= null
) {
278 if (mCurrentFile
.fileExists()) {
279 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
280 } // 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
283 /// Default to root if mCurrentDir was not found
284 if (mCurrentDir
== null
) {
285 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
290 private void initFileDetailsInDualPane() {
291 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
292 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
293 if (mCurrentFile
!= null
) {
294 transaction
.replace(R
.id
.file_details_container
,
295 new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)),
296 FileDetailFragment
.FTAG
); // empty FileDetailFragment
299 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
),
300 FileDetailFragment
.FTAG
); // empty FileDetailFragment
302 transaction
.commit();
308 public void onDestroy() {
310 if (mDownloadConnection
!= null
)
311 unbindService(mDownloadConnection
);
312 if (mUploadConnection
!= null
)
313 unbindService(mUploadConnection
);
318 public boolean onCreateOptionsMenu(Menu menu
) {
319 MenuInflater inflater
= getSherlock().getMenuInflater();
320 inflater
.inflate(R
.menu
.menu
, menu
);
325 public boolean onOptionsItemSelected(MenuItem item
) {
326 boolean retval
= true
;
327 switch (item
.getItemId()) {
328 case R
.id
.createDirectoryItem
: {
329 showDialog(DIALOG_CREATE_DIR
);
332 case R
.id
.startSync
: {
333 startSynchronization();
336 case R
.id
.action_upload
: {
337 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
340 case R
.id
.action_settings
: {
341 Intent settingsIntent
= new Intent(this, Preferences
.class);
342 startActivity(settingsIntent
);
345 case android
.R
.id
.home
: {
346 if (mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0) {
352 retval
= super.onOptionsItemSelected(item
);
357 private void startSynchronization() {
358 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
359 Bundle bundle
= new Bundle();
360 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
361 ContentResolver
.requestSync(
362 AccountUtils
.getCurrentOwnCloudAccount(this),
363 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
368 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
369 int i
= itemPosition
;
373 // the next operation triggers a new call to this method, but it's necessary to
374 // ensure that the name exposed in the action bar is the current directory when the
375 // user selected it in the navigation list
376 if (itemPosition
!= 0)
377 getSupportActionBar().setSelectedNavigationItem(0);
382 * Called, when the user selected something for uploading
384 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
386 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
387 && (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
388 requestSimpleUpload(data
, resultCode
);
390 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
391 && (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
392 requestMultipleUpload(data
, resultCode
);
397 private void requestMultipleUpload(Intent data
, int resultCode
) {
398 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
399 if (filePaths
!= null
) {
400 String
[] remotePaths
= new String
[filePaths
.length
];
401 String remotePathBase
= "";
402 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
403 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
405 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
406 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
407 for (int j
= 0; j
< remotePaths
.length
; j
++) {
408 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
411 Intent i
= new Intent(this, FileUploader
.class);
412 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
413 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
414 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
415 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
416 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
417 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
421 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
422 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
429 private void requestSimpleUpload(Intent data
, int resultCode
) {
430 String filepath
= null
;
432 Uri selectedImageUri
= data
.getData();
434 String filemanagerstring
= selectedImageUri
.getPath();
435 String selectedImagePath
= getPath(selectedImageUri
);
437 if (selectedImagePath
!= null
)
438 filepath
= selectedImagePath
;
440 filepath
= filemanagerstring
;
442 } catch (Exception e
) {
443 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
447 if (filepath
== null
) {
448 Log
.e("FileDisplay", "Couldnt resolve path to file");
449 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
455 Intent i
= new Intent(this, FileUploader
.class);
456 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
457 String remotepath
= new String();
458 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
459 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
461 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
462 remotepath
+= OCFile
.PATH_SEPARATOR
;
463 remotepath
+= new File(filepath
).getName();
465 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
466 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
467 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
468 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
469 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
475 public void onBackPressed() {
476 if (mDirectories
.getCount() <= 1) {
481 mFileList
.onNavigateUp();
482 mCurrentDir
= mFileList
.getCurrentFile();
485 // Resets the FileDetailsFragment on Tablets so that it always
487 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
488 FileDetailFragment
.FTAG
);
489 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
490 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
491 transaction
.remove(fileDetails
);
492 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
),
493 FileDetailFragment
.FTAG
);
494 transaction
.commit();
498 if (mCurrentDir
.getParentId() == 0) {
499 ActionBar actionBar
= getSupportActionBar();
500 actionBar
.setDisplayHomeAsUpEnabled(false
);
505 protected void onSaveInstanceState(Bundle outState
) {
506 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
507 Log
.d(getClass().toString(), "onSaveInstanceState() start");
508 super.onSaveInstanceState(outState
);
509 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
511 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
512 if (fragment
!= null
) {
513 OCFile file
= fragment
.getDisplayedFile();
515 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
519 Log
.d(getClass().toString(), "onSaveInstanceState() end");
523 protected void onResume() {
524 Log
.d(getClass().toString(), "onResume() start");
527 if (AccountUtils
.accountsAreSetup(this)) {
529 if (mStorageManager
== null
) {
530 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
531 initDataFromCurrentAccount();
533 initFileDetailsInDualPane();
537 // Listen for sync messages
538 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
539 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
540 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
542 // Listen for upload messages
543 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
544 mUploadFinishReceiver
= new UploadFinishReceiver();
545 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
547 // Listen for download messages
548 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
549 mDownloadFinishReceiver
= new DownloadFinishReceiver();
550 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
552 // List current directory
553 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
557 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
558 showDialog(DIALOG_SETUP_ACCOUNT
);
561 Log
.d(getClass().toString(), "onResume() end");
566 protected void onPause() {
567 Log
.d(getClass().toString(), "onPause() start");
569 if (mSyncBroadcastReceiver
!= null
) {
570 unregisterReceiver(mSyncBroadcastReceiver
);
571 mSyncBroadcastReceiver
= null
;
573 if (mUploadFinishReceiver
!= null
) {
574 unregisterReceiver(mUploadFinishReceiver
);
575 mUploadFinishReceiver
= null
;
577 if (mDownloadFinishReceiver
!= null
) {
578 unregisterReceiver(mDownloadFinishReceiver
);
579 mDownloadFinishReceiver
= null
;
581 if (!AccountUtils
.accountsAreSetup(this)) {
582 dismissDialog(DIALOG_SETUP_ACCOUNT
);
585 Log
.d(getClass().toString(), "onPause() end");
590 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
591 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
592 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
598 protected Dialog
onCreateDialog(int id
) {
599 Dialog dialog
= null
;
600 AlertDialog
.Builder builder
;
602 case DIALOG_SETUP_ACCOUNT
: {
603 builder
= new AlertDialog
.Builder(this);
604 builder
.setTitle(R
.string
.main_tit_accsetup
);
605 builder
.setMessage(R
.string
.main_wrn_accsetup
);
606 builder
.setCancelable(false
);
607 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
608 public void onClick(DialogInterface dialog
, int which
) {
609 createFirstAccount();
613 String message
= String
.format(getString(R
.string
.common_exit
), getString(R
.string
.app_name
));
614 builder
.setNegativeButton(message
, new OnClickListener() {
615 public void onClick(DialogInterface dialog
, int which
) {
620 //builder.setNegativeButton(android.R.string.cancel, this);
621 dialog
= builder
.create();
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
, new OnClickListener() {
632 public void onClick(DialogInterface dialog
, int which
) {
633 String directoryName
= dirNameInput
.getText().toString();
634 if (directoryName
.trim().length() == 0) {
639 // Figure out the path where the dir needs to be created
641 if (mCurrentDir
== null
) {
642 // this is just a patch; we should ensure that
643 // 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
655 .getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
660 showDialog(DIALOG_SHORT_WAIT
);
663 builder
.setNegativeButton(R
.string
.common_cancel
, 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(R
.string
.wait_a_moment
));
674 working_dialog
.setIndeterminate(true
);
675 working_dialog
.setCancelable(false
);
676 dialog
= working_dialog
;
679 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
680 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
681 getString(R
.string
.actionbar_upload_from_apps
), getString(R
.string
.actionbar_failed_instant_upload
) };
682 builder
= new AlertDialog
.Builder(this);
683 builder
.setTitle(R
.string
.actionbar_upload
);
684 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
685 public void onClick(DialogInterface dialog
, int item
) {
688 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
689 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
,
690 AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this));
691 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
693 // TODO create and handle new fragment
694 // LocalFileListFragment
696 } else if (item
== 1) {
697 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
698 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
699 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
700 ACTION_SELECT_CONTENT_FROM_APPS
);
701 } else if (item
== 2) {
702 Account account
= AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this);
703 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
704 action
.putExtra(FileUploader
.KEY_ACCOUNT
, account
);
705 startActivity(action
);
709 dialog
= builder
.create();
712 case DIALOG_SSL_VALIDATOR
: {
713 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
716 case DIALOG_CERT_NOT_SAVED
: {
717 builder
= new AlertDialog
.Builder(this);
718 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
719 builder
.setCancelable(false
);
720 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
722 public void onClick(DialogInterface dialog
, int which
) {
726 dialog
= builder
.create();
738 * Translates a content URI of an image to a physical path
740 * @param uri The URI to resolve
741 * @return The path to the image or null if it could not be found
743 public String
getPath(Uri uri
) {
744 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
745 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
746 if (cursor
!= null
) {
747 int column_index
= cursor
.getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
748 cursor
.moveToFirst();
749 return cursor
.getString(column_index
);
755 * Pushes a directory to the drop down list
756 * @param directory to push
757 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
759 public void pushDirname(OCFile directory
) {
760 if(!directory
.isDirectory()){
761 throw new IllegalArgumentException("Only directories may be pushed!");
763 mDirectories
.insert(directory
.getFileName(), 0);
764 mCurrentDir
= directory
;
768 * Pops a directory name from the drop down list
769 * @return True, unless the stack is empty
771 public boolean popDirname() {
772 mDirectories
.remove(mDirectories
.getItem(0));
773 return !mDirectories
.isEmpty();
776 private class DirectoryCreator
implements Runnable
{
777 private String mTargetPath
;
778 private Account mAccount
;
779 private Handler mHandler
;
781 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
782 mTargetPath
= targetPath
;
789 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
790 boolean created
= wdc
.createDirectory(mTargetPath
);
792 mHandler
.post(new Runnable() {
795 dismissDialog(DIALOG_SHORT_WAIT
);
797 // Save new directory in local database
798 OCFile newDir
= new OCFile(mTargetPath
);
799 newDir
.setMimetype("DIR");
800 newDir
.setParentId(mCurrentDir
.getFileId());
801 mStorageManager
.saveFile(newDir
);
803 // Display the new folder right away
804 mFileList
.listDirectory();
809 mHandler
.post(new Runnable() {
812 dismissDialog(DIALOG_SHORT_WAIT
);
814 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
,
818 } catch (NotFoundException e
) {
819 Log
.e(TAG
, "Error while trying to show fail message ", e
);
828 // Custom array adapter to override text colors
829 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
831 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
835 public View
getView(int position
, View convertView
, ViewGroup parent
) {
836 View v
= super.getView(position
, convertView
, parent
);
838 ((TextView
) v
).setTextColor(getResources().getColorStateList(android
.R
.color
.white
));
842 public View
getDropDownView(int position
, View convertView
, ViewGroup parent
) {
843 View v
= super.getDropDownView(position
, convertView
, parent
);
845 ((TextView
) v
).setTextColor(getResources().getColorStateList(android
.R
.color
.white
));
852 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
855 * {@link BroadcastReceiver} to enable syncing feedback in UI
858 public void onReceive(Context context
, Intent intent
) {
859 boolean inProgress
= intent
.getBooleanExtra(FileSyncService
.IN_PROGRESS
, false
);
860 String accountName
= intent
.getStringExtra(FileSyncService
.ACCOUNT_NAME
);
862 Log
.d("FileDisplay", "sync of account " + accountName
+ " is in_progress: " + inProgress
);
864 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
866 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
868 boolean fillBlankRoot
= false
;
869 if (mCurrentDir
== null
) {
870 mCurrentDir
= mStorageManager
.getFileByPath("/");
871 fillBlankRoot
= (mCurrentDir
!= null
);
874 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath()
875 .equals(synchFolderRemotePath
))) || fillBlankRoot
) {
877 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
878 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
879 .findFragmentById(R
.id
.fileList
);
880 if (fileListFragment
!= null
) {
881 fileListFragment
.listDirectory(mCurrentDir
);
885 setSupportProgressBarIndeterminateVisibility(inProgress
);
886 removeStickyBroadcast(intent
);
890 RemoteOperationResult synchResult
= (RemoteOperationResult
) intent
891 .getSerializableExtra(FileSyncService
.SYNC_RESULT
);
892 if (synchResult
!= null
) {
893 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
894 mLastSslUntrustedServerResult
= synchResult
;
895 showDialog(DIALOG_SSL_VALIDATOR
);
902 private class UploadFinishReceiver
extends BroadcastReceiver
{
904 * Once the file upload has finished -> update view
905 * @author David A. Velasco
906 * {@link BroadcastReceiver} to enable upload feedback in UI
909 public void onReceive(Context context
, Intent intent
) {
910 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
911 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
912 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
913 boolean isDescendant
= (mCurrentDir
!= null
) && (uploadedRemotePath
!= null
)
914 && (uploadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
915 if (sameAccount
&& isDescendant
) {
916 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
917 .findFragmentById(R
.id
.fileList
);
918 if (fileListFragment
!= null
) {
919 fileListFragment
.listDirectory();
928 * Once the file download has finished -> update view
930 private class DownloadFinishReceiver
extends BroadcastReceiver
{
932 public void onReceive(Context context
, Intent intent
) {
933 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
934 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
935 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
936 boolean isDescendant
= (mCurrentDir
!= null
) && (downloadedRemotePath
!= null
)
937 && (downloadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
938 if (sameAccount
&& isDescendant
) {
939 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
940 .findFragmentById(R
.id
.fileList
);
941 if (fileListFragment
!= null
) {
942 fileListFragment
.listDirectory();
955 public DataStorageManager
getStorageManager() {
956 return mStorageManager
;
964 public void onDirectoryClick(OCFile directory
) {
965 pushDirname(directory
);
966 ActionBar actionBar
= getSupportActionBar();
967 actionBar
.setDisplayHomeAsUpEnabled(true
);
970 // Resets the FileDetailsFragment on Tablets so that it always displays
971 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
972 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
973 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
974 transaction
.remove(fileDetails
);
975 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
),
976 FileDetailFragment
.FTAG
);
977 transaction
.commit();
987 public void onFileClick(OCFile file
) {
989 // If we are on a large device -> update fragment
991 // 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'
992 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
994 .replace(R
.id
.file_details_container
,
995 new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)),
996 FileDetailFragment
.FTAG
);
997 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
998 transaction
.commit();
1000 } else { // small or medium screen device -> new Activity
1001 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
1002 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
1003 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
1004 startActivity(showDetailsIntent
);
1013 public OCFile
getInitialDirectory() {
1022 public void onFileStateChanged() {
1023 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(
1025 if (fileListFragment
!= null
) {
1026 fileListFragment
.listDirectory();
1035 public FileDownloaderBinder
getFileDownloaderBinder() {
1036 return mDownloaderBinder
;
1044 public FileUploaderBinder
getFileUploaderBinder() {
1045 return mUploaderBinder
;
1049 /** Defines callbacks for service binding, passed to bindService() */
1050 private class ListServiceConnection
implements ServiceConnection
{
1053 public void onServiceConnected(ComponentName component
, IBinder service
) {
1054 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1055 Log
.d(TAG
, "Download service connected");
1056 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1057 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1058 Log
.d(TAG
, "Upload service connected");
1059 mUploaderBinder
= (FileUploaderBinder
) service
;
1063 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1064 if (mFileList
!= null
)
1065 mFileList
.listDirectory();
1067 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
1068 FileDetailFragment
.FTAG
);
1069 if (fragment
!= null
)
1070 fragment
.updateFileDetails(false
);
1075 public void onServiceDisconnected(ComponentName component
) {
1076 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1077 Log
.d(TAG
, "Download service disconnected");
1078 mDownloaderBinder
= null
;
1079 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1080 Log
.d(TAG
, "Upload service disconnected");
1081 mUploaderBinder
= null
;
1089 * Launch an intent to request the PIN code to the user before letting him use the app
1091 private void requestPinCode() {
1092 boolean pinStart
= false
;
1093 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1094 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1096 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1097 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1104 public void onSavedCertificate() {
1105 startSynchronization();
1109 public void onFailedSavingCertificate() {
1110 showDialog(DIALOG_CERT_NOT_SAVED
);
1115 * Updates the view associated to the activity after the finish of some operation over files
1116 * in the current account.
1118 * @param operation Removal operation performed.
1119 * @param result Result of the removal.
1122 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1123 if (operation
instanceof RemoveFileOperation
) {
1124 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1126 } else if (operation
instanceof RenameFileOperation
) {
1127 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1129 } else if (operation
instanceof SynchronizeFileOperation
) {
1130 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1136 * Updates the view associated to the activity after the finish of an operation trying to remove a
1139 * @param operation Removal operation performed.
1140 * @param result Result of the removal.
1142 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1143 dismissDialog(DIALOG_SHORT_WAIT
);
1144 if (result
.isSuccess()) {
1145 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1147 OCFile removedFile
= operation
.getFile();
1149 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
1150 FileDetailFragment
.FTAG
);
1151 if (details
!= null
&& removedFile
.equals(details
.getDisplayedFile())) {
1152 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
1153 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty
1154 // FileDetailFragment
1155 transaction
.commit();
1158 if (mStorageManager
.getFileById(removedFile
.getParentId()).equals(mCurrentDir
)) {
1159 mFileList
.listDirectory();
1163 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1165 if (result
.isSslRecoverableException()) {
1166 mLastSslUntrustedServerResult
= result
;
1167 showDialog(DIALOG_SSL_VALIDATOR
);
1173 * Updates the view associated to the activity after the finish of an operation trying to rename a
1176 * @param operation Renaming operation performed.
1177 * @param result Result of the renaming.
1179 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1180 dismissDialog(DIALOG_SHORT_WAIT
);
1181 OCFile renamedFile
= operation
.getFile();
1182 if (result
.isSuccess()) {
1184 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
1185 FileDetailFragment
.FTAG
);
1186 if (details
!= null
&& renamedFile
.equals(details
.getDisplayedFile())) {
1187 details
.updateFileDetails(renamedFile
, AccountUtils
.getCurrentOwnCloudAccount(this));
1190 if (mStorageManager
.getFileById(renamedFile
.getParentId()).equals(mCurrentDir
)) {
1191 mFileList
.listDirectory();
1195 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1196 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1198 // TODO throw again the new rename dialog
1200 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1202 if (result
.isSslRecoverableException()) {
1203 mLastSslUntrustedServerResult
= result
;
1204 showDialog(DIALOG_SSL_VALIDATOR
);
1210 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1211 dismissDialog(DIALOG_SHORT_WAIT
);
1212 OCFile syncedFile
= operation
.getLocalFile();
1213 if (!result
.isSuccess()) {
1214 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1215 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1216 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1217 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
1221 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1226 if (operation
.transferWasRequested()) {
1227 mFileList
.listDirectory();
1228 onTransferStateChanged(syncedFile
, true
, true
);
1231 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1242 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1243 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1244 if (fileListFragment != null) {
1245 fileListFragment.listDirectory();
1248 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(
1249 FileDetailFragment
.FTAG
);
1250 if (details
!= null
&& file
.equals(details
.getDisplayedFile())) {
1251 if (downloading
|| uploading
) {
1252 details
.updateFileDetails(file
, AccountUtils
.getCurrentOwnCloudAccount(this));
1254 details
.updateFileDetails(downloading
|| uploading
);