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
.net
.Uri
;
43 import android
.os
.Bundle
;
44 import android
.os
.Handler
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.FragmentTransaction
;
49 import android
.util
.Log
;
50 import android
.view
.View
;
51 import android
.view
.ViewGroup
;
52 import android
.widget
.ArrayAdapter
;
53 import android
.widget
.EditText
;
54 import android
.widget
.TextView
;
55 import android
.widget
.Toast
;
57 import com
.actionbarsherlock
.app
.ActionBar
;
58 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
59 import com
.actionbarsherlock
.app
.SherlockFragmentActivity
;
60 import com
.actionbarsherlock
.view
.Menu
;
61 import com
.actionbarsherlock
.view
.MenuInflater
;
62 import com
.actionbarsherlock
.view
.MenuItem
;
63 import com
.actionbarsherlock
.view
.Window
;
64 import com
.owncloud
.android
.AccountUtils
;
65 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
66 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
67 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
68 import com
.owncloud
.android
.datamodel
.OCFile
;
69 import com
.owncloud
.android
.files
.services
.FileDownloader
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
71 import com
.owncloud
.android
.files
.services
.FileObserverService
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
74 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
75 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
76 import com
.owncloud
.android
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
79 import com
.owncloud
.android
.operations
.RenameFileOperation
;
80 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
81 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
82 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
83 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
84 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
85 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
87 import com
.owncloud
.android
.R
;
88 import eu
.alefzero
.webdav
.WebdavClient
;
91 * Displays, what files the user has available in his ownCloud.
93 * @author Bartek Przybylski
97 public class FileDisplayActivity
extends SherlockFragmentActivity
implements
98 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, OnRemoteOperationListener
{
100 private ArrayAdapter
<String
> mDirectories
;
101 private OCFile mCurrentDir
= null
;
102 private OCFile mCurrentFile
= null
;
104 private DataStorageManager mStorageManager
;
105 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
106 private UploadFinishReceiver mUploadFinishReceiver
;
107 private DownloadFinishReceiver mDownloadFinishReceiver
;
108 private FileDownloaderBinder mDownloaderBinder
= null
;
109 private FileUploaderBinder mUploaderBinder
= null
;
110 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
111 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
113 private OCFileListFragment mFileList
;
115 private boolean mDualPane
;
117 private static final int DIALOG_SETUP_ACCOUNT
= 0;
118 private static final int DIALOG_CREATE_DIR
= 1;
119 private static final int DIALOG_ABOUT_APP
= 2;
120 public static final int DIALOG_SHORT_WAIT
= 3;
121 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 4;
122 private static final int DIALOG_SSL_VALIDATOR
= 5;
123 private static final int DIALOG_CERT_NOT_SAVED
= 6;
126 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
127 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
129 private static final String TAG
= "FileDisplayActivity";
132 public void onCreate(Bundle savedInstanceState
) {
133 Log
.d(getClass().toString(), "onCreate() start");
134 super.onCreate(savedInstanceState
);
136 /// Load of parameters from received intent
137 mCurrentDir
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_FILE
); // no check necessary, mCurrenDir == null if the parameter is not in the intent
138 Account account
= getIntent().getParcelableExtra(FileDetailFragment
.EXTRA_ACCOUNT
);
140 AccountUtils
.setCurrentOwnCloudAccount(this, account
.name
);
142 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
143 if(savedInstanceState
!= null
) {
144 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
145 mCurrentDir
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
148 if (!AccountUtils
.accountsAreSetup(this)) {
149 /// no account available: FORCE ACCOUNT CREATION
150 mStorageManager
= null
;
151 createFirstAccount();
153 } else { /// at least an account is available
155 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
159 mUploadConnection
= new ListServiceConnection();
160 mDownloadConnection
= new ListServiceConnection();
161 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
162 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
164 // PIN CODE request ; best location is to decide, let's try this first
165 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
170 Intent observer_intent
= new Intent(this, FileObserverService
.class);
171 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
172 startService(observer_intent
);
176 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
178 // Drop-down navigation
179 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
180 OCFile currFile
= mCurrentDir
;
181 while(currFile
!= null
&& currFile
.getFileName() != OCFile
.PATH_SEPARATOR
) {
182 mDirectories
.add(currFile
.getFileName());
183 currFile
= mStorageManager
.getFileById(currFile
.getParentId());
185 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
189 mFileList
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
190 mDualPane
= (findViewById(R
.id
.file_details_container
) != null
);
192 initFileDetailsInDualPane();
196 ActionBar actionBar
= getSupportActionBar();
197 actionBar
.setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
198 actionBar
.setDisplayHomeAsUpEnabled(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0);
199 actionBar
.setDisplayShowTitleEnabled(false
);
200 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
201 actionBar
.setListNavigationCallbacks(mDirectories
, this);
202 setSupportProgressBarIndeterminateVisibility(false
); // always AFTER setContentView(...) ; to workaround bug in its implementation
204 Log
.d(getClass().toString(), "onCreate() end");
209 * Launches the account creation activity. To use when no ownCloud account is available
211 private void createFirstAccount() {
212 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
213 intent
.putExtra(android
.provider
.Settings
.EXTRA_AUTHORITIES
, new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
214 startActivity(intent
); // the new activity won't be created until this.onStart() and this.onResume() are finished;
219 * Load of state dependent of the existence of an ownCloud account
221 private void initDataFromCurrentAccount() {
222 /// Storage manager initialization - access to local database
223 mStorageManager
= new FileDataStorageManager(
224 AccountUtils
.getCurrentOwnCloudAccount(this),
225 getContentResolver());
227 /// Check if mCurrentDir is a directory
228 if(mCurrentDir
!= null
&& !mCurrentDir
.isDirectory()) {
229 mCurrentFile
= mCurrentDir
;
230 mCurrentDir
= mStorageManager
.getFileById(mCurrentDir
.getParentId());
233 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
234 if (mCurrentDir
!= null
) {
235 mCurrentDir
= mStorageManager
.getFileByPath(mCurrentDir
.getRemotePath()); // mCurrentDir == null if it is not in the current account
237 if (mCurrentFile
!= null
) {
238 if (mCurrentFile
.fileExists()) {
239 mCurrentFile
= mStorageManager
.getFileByPath(mCurrentFile
.getRemotePath()); // mCurrentFile == null if it is not in the current account
240 } // 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
243 /// Default to root if mCurrentDir was not found
244 if (mCurrentDir
== null
) {
245 mCurrentDir
= mStorageManager
.getFileByPath("/"); // will be NULL if the database was never synchronized
250 private void initFileDetailsInDualPane() {
251 if (mDualPane
&& getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
) == null
) {
252 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
253 if (mCurrentFile
!= null
) {
254 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(mCurrentFile
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
); // empty FileDetailFragment
257 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
259 transaction
.commit();
265 public void onDestroy() {
267 if (mDownloadConnection
!= null
)
268 unbindService(mDownloadConnection
);
269 if (mUploadConnection
!= null
)
270 unbindService(mUploadConnection
);
275 public boolean onCreateOptionsMenu(Menu menu
) {
276 MenuInflater inflater
= getSherlock().getMenuInflater();
277 inflater
.inflate(R
.menu
.menu
, menu
);
282 public boolean onOptionsItemSelected(MenuItem item
) {
283 boolean retval
= true
;
284 switch (item
.getItemId()) {
285 case R
.id
.createDirectoryItem
: {
286 showDialog(DIALOG_CREATE_DIR
);
289 case R
.id
.startSync
: {
290 startSynchronization();
293 case R
.id
.action_upload
: {
294 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
297 case R
.id
.action_settings
: {
298 Intent settingsIntent
= new Intent(this, Preferences
.class);
299 startActivity(settingsIntent
);
302 case R
.id
.about_app
: {
303 showDialog(DIALOG_ABOUT_APP
);
306 case android
.R
.id
.home
: {
307 if(mCurrentDir
!= null
&& mCurrentDir
.getParentId() != 0){
313 retval
= super.onOptionsItemSelected(item
);
318 private void startSynchronization() {
319 ContentResolver
.cancelSync(null
, AccountAuthenticator
.AUTH_TOKEN_TYPE
); // cancel the current synchronizations of any ownCloud account
320 Bundle bundle
= new Bundle();
321 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
322 ContentResolver
.requestSync(
323 AccountUtils
.getCurrentOwnCloudAccount(this),
324 AccountAuthenticator
.AUTH_TOKEN_TYPE
, bundle
);
329 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
330 int i
= itemPosition
;
334 // the next operation triggers a new call to this method, but it's necessary to
335 // ensure that the name exposed in the action bar is the current directory when the
336 // user selected it in the navigation list
337 if (itemPosition
!= 0)
338 getSupportActionBar().setSelectedNavigationItem(0);
343 * Called, when the user selected something for uploading
345 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
347 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& resultCode
== RESULT_OK
) {
348 requestSimpleUpload(data
);
350 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& resultCode
== RESULT_OK
) {
351 requestMultipleUpload(data
);
356 private void requestMultipleUpload(Intent data
) {
357 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
358 if (filePaths
!= null
) {
359 String
[] remotePaths
= new String
[filePaths
.length
];
360 String remotePathBase
= "";
361 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
362 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
364 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
365 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
366 for (int j
= 0; j
< remotePaths
.length
; j
++) {
367 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
370 Intent i
= new Intent(this, FileUploader
.class);
371 i
.putExtra(FileUploader
.KEY_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
372 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
373 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
374 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
378 Log
.d("FileDisplay", "User clicked on 'Update' with no selection");
379 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
386 private void requestSimpleUpload(Intent data
) {
387 String filepath
= null
;
389 Uri selectedImageUri
= data
.getData();
391 String filemanagerstring
= selectedImageUri
.getPath();
392 String selectedImagePath
= getPath(selectedImageUri
);
394 if (selectedImagePath
!= null
)
395 filepath
= selectedImagePath
;
397 filepath
= filemanagerstring
;
399 } catch (Exception e
) {
400 Log
.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
404 if (filepath
== null
) {
405 Log
.e("FileDisplay", "Couldnt resolve path to file");
406 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
412 Intent i
= new Intent(this, FileUploader
.class);
413 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
414 AccountUtils
.getCurrentOwnCloudAccount(this));
415 String remotepath
= new String();
416 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
417 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
419 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
420 remotepath
+= OCFile
.PATH_SEPARATOR
;
421 remotepath
+= new File(filepath
).getName();
423 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
424 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
425 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
431 public void onBackPressed() {
432 if (mDirectories
.getCount() <= 1) {
437 mFileList
.onNavigateUp();
438 mCurrentDir
= mFileList
.getCurrentFile();
441 // Resets the FileDetailsFragment on Tablets so that it always displays
442 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
443 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
444 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
445 transaction
.remove(fileDetails
);
446 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
447 transaction
.commit();
451 if(mCurrentDir
.getParentId() == 0){
452 ActionBar actionBar
= getSupportActionBar();
453 actionBar
.setDisplayHomeAsUpEnabled(false
);
458 protected void onSaveInstanceState(Bundle outState
) {
459 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
460 Log
.d(getClass().toString(), "onSaveInstanceState() start");
461 super.onSaveInstanceState(outState
);
462 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mCurrentDir
);
464 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
465 if (fragment
!= null
) {
466 OCFile file
= fragment
.getDisplayedFile();
468 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, file
);
472 Log
.d(getClass().toString(), "onSaveInstanceState() end");
476 protected void onResume() {
477 Log
.d(getClass().toString(), "onResume() start");
480 if (AccountUtils
.accountsAreSetup(this)) {
482 if (mStorageManager
== null
) {
483 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
484 initDataFromCurrentAccount();
486 initFileDetailsInDualPane();
490 // Listen for sync messages
491 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.SYNC_MESSAGE
);
492 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
493 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
495 // Listen for upload messages
496 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
497 mUploadFinishReceiver
= new UploadFinishReceiver();
498 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
500 // Listen for download messages
501 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
502 mDownloadFinishReceiver
= new DownloadFinishReceiver();
503 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
505 // List current directory
506 mFileList
.listDirectory(mCurrentDir
); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
510 mStorageManager
= null
; // an invalid object will be there if all the ownCloud accounts are removed
511 showDialog(DIALOG_SETUP_ACCOUNT
);
514 Log
.d(getClass().toString(), "onResume() end");
519 protected void onPause() {
520 Log
.d(getClass().toString(), "onPause() start");
522 if (mSyncBroadcastReceiver
!= null
) {
523 unregisterReceiver(mSyncBroadcastReceiver
);
524 mSyncBroadcastReceiver
= null
;
526 if (mUploadFinishReceiver
!= null
) {
527 unregisterReceiver(mUploadFinishReceiver
);
528 mUploadFinishReceiver
= null
;
530 if (mDownloadFinishReceiver
!= null
) {
531 unregisterReceiver(mDownloadFinishReceiver
);
532 mDownloadFinishReceiver
= null
;
534 if (!AccountUtils
.accountsAreSetup(this)) {
535 dismissDialog(DIALOG_SETUP_ACCOUNT
);
538 Log
.d(getClass().toString(), "onPause() end");
543 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
544 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
545 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
551 protected Dialog
onCreateDialog(int id
) {
552 Dialog dialog
= null
;
553 AlertDialog
.Builder builder
;
555 case DIALOG_SETUP_ACCOUNT
: {
556 builder
= new AlertDialog
.Builder(this);
557 builder
.setTitle(R
.string
.main_tit_accsetup
);
558 builder
.setMessage(R
.string
.main_wrn_accsetup
);
559 builder
.setCancelable(false
);
560 builder
.setPositiveButton(android
.R
.string
.ok
, new OnClickListener() {
561 public void onClick(DialogInterface dialog
, int which
) {
562 createFirstAccount();
566 builder
.setNegativeButton(R
.string
.common_exit
, new OnClickListener() {
567 public void onClick(DialogInterface dialog
, int which
) {
572 //builder.setNegativeButton(android.R.string.cancel, this);
573 dialog
= builder
.create();
576 case DIALOG_ABOUT_APP
: {
577 builder
= new AlertDialog
.Builder(this);
578 builder
.setTitle(getString(R
.string
.about_title
));
581 pkg
= getPackageManager().getPackageInfo(getPackageName(), 0);
582 builder
.setMessage(String
.format(getString(R
.string
.about_message
), pkg
.versionName
));
583 builder
.setIcon(android
.R
.drawable
.ic_menu_info_details
);
584 dialog
= builder
.create();
585 } catch (NameNotFoundException e
) {
588 Log
.e(TAG
, "Error while showing about dialog", e
);
592 case DIALOG_CREATE_DIR
: {
593 builder
= new Builder(this);
594 final EditText dirNameInput
= new EditText(getBaseContext());
595 builder
.setView(dirNameInput
);
596 builder
.setTitle(R
.string
.uploader_info_dirname
);
597 int typed_color
= getResources().getColor(R
.color
.setup_text_typed
);
598 dirNameInput
.setTextColor(typed_color
);
599 builder
.setPositiveButton(android
.R
.string
.ok
,
600 new OnClickListener() {
601 public void onClick(DialogInterface dialog
, int which
) {
602 String directoryName
= dirNameInput
.getText().toString();
603 if (directoryName
.trim().length() == 0) {
608 // Figure out the path where the dir needs to be created
610 if (mCurrentDir
== null
) {
611 // this is just a patch; we should ensure that mCurrentDir never is null
612 if (!mStorageManager
.fileExists(OCFile
.PATH_SEPARATOR
)) {
613 OCFile file
= new OCFile(OCFile
.PATH_SEPARATOR
);
614 mStorageManager
.saveFile(file
);
616 mCurrentDir
= mStorageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
);
618 path
= FileDisplayActivity
.this.mCurrentDir
.getRemotePath();
621 path
+= directoryName
+ OCFile
.PATH_SEPARATOR
;
622 Thread thread
= new Thread(new DirectoryCreator(path
, AccountUtils
.getCurrentOwnCloudAccount(FileDisplayActivity
.this), new Handler()));
627 showDialog(DIALOG_SHORT_WAIT
);
630 builder
.setNegativeButton(R
.string
.common_cancel
,
631 new OnClickListener() {
632 public void onClick(DialogInterface dialog
, int which
) {
636 dialog
= builder
.create();
639 case DIALOG_SHORT_WAIT
: {
640 ProgressDialog working_dialog
= new ProgressDialog(this);
641 working_dialog
.setMessage(getResources().getString(
642 R
.string
.wait_a_moment
));
643 working_dialog
.setIndeterminate(true
);
644 working_dialog
.setCancelable(false
);
645 dialog
= working_dialog
;
648 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
649 final String
[] items
= { getString(R
.string
.actionbar_upload_files
),
650 getString(R
.string
.actionbar_upload_from_apps
) };
651 builder
= new AlertDialog
.Builder(this);
652 builder
.setTitle(R
.string
.actionbar_upload
);
653 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
654 public void onClick(DialogInterface dialog
, int item
) {
657 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
658 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
660 // TODO create and handle new fragment LocalFileListFragment
662 } else if (item
== 1) {
663 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
664 action
= action
.setType("*/*")
665 .addCategory(Intent
.CATEGORY_OPENABLE
);
666 startActivityForResult(
667 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
668 ACTION_SELECT_CONTENT_FROM_APPS
);
672 dialog
= builder
.create();
675 case DIALOG_SSL_VALIDATOR
: {
676 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
679 case DIALOG_CERT_NOT_SAVED
: {
680 builder
= new AlertDialog
.Builder(this);
681 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
682 builder
.setCancelable(false
);
683 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
685 public void onClick(DialogInterface dialog
, int which
) {
689 dialog
= builder
.create();
701 * Translates a content URI of an image to a physical path
703 * @param uri The URI to resolve
704 * @return The path to the image or null if it could not be found
706 public String
getPath(Uri uri
) {
707 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
708 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
709 if (cursor
!= null
) {
710 int column_index
= cursor
711 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
712 cursor
.moveToFirst();
713 return cursor
.getString(column_index
);
719 * Pushes a directory to the drop down list
720 * @param directory to push
721 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
723 public void pushDirname(OCFile directory
) {
724 if(!directory
.isDirectory()){
725 throw new IllegalArgumentException("Only directories may be pushed!");
727 mDirectories
.insert(directory
.getFileName(), 0);
728 mCurrentDir
= directory
;
732 * Pops a directory name from the drop down list
733 * @return True, unless the stack is empty
735 public boolean popDirname() {
736 mDirectories
.remove(mDirectories
.getItem(0));
737 return !mDirectories
.isEmpty();
740 private class DirectoryCreator
implements Runnable
{
741 private String mTargetPath
;
742 private Account mAccount
;
743 private Handler mHandler
;
745 public DirectoryCreator(String targetPath
, Account account
, Handler handler
) {
746 mTargetPath
= targetPath
;
753 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
754 boolean created
= wdc
.createDirectory(mTargetPath
);
756 mHandler
.post(new Runnable() {
759 dismissDialog(DIALOG_SHORT_WAIT
);
761 // Save new directory in local database
762 OCFile newDir
= new OCFile(mTargetPath
);
763 newDir
.setMimetype("DIR");
764 newDir
.setParentId(mCurrentDir
.getFileId());
765 mStorageManager
.saveFile(newDir
);
767 // Display the new folder right away
768 mFileList
.listDirectory();
773 mHandler
.post(new Runnable() {
776 dismissDialog(DIALOG_SHORT_WAIT
);
778 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
781 } catch (NotFoundException e
) {
782 Log
.e(TAG
, "Error while trying to show fail message " , e
);
791 // Custom array adapter to override text colors
792 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
794 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
798 public View
getView(int position
, View convertView
, ViewGroup parent
) {
799 View v
= super.getView(position
, convertView
, parent
);
801 ((TextView
) v
).setTextColor(getResources().getColorStateList(
802 android
.R
.color
.white
));
806 public View
getDropDownView(int position
, View convertView
,
808 View v
= super.getDropDownView(position
, convertView
, parent
);
810 ((TextView
) v
).setTextColor(getResources().getColorStateList(
811 android
.R
.color
.white
));
818 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
821 * {@link BroadcastReceiver} to enable syncing feedback in UI
824 public void onReceive(Context context
, Intent intent
) {
825 boolean inProgress
= intent
.getBooleanExtra(
826 FileSyncService
.IN_PROGRESS
, false
);
827 String accountName
= intent
828 .getStringExtra(FileSyncService
.ACCOUNT_NAME
);
830 Log
.d("FileDisplay", "sync of account " + accountName
831 + " is in_progress: " + inProgress
);
833 if (accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
)) {
835 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
837 boolean fillBlankRoot
= false
;
838 if (mCurrentDir
== null
) {
839 mCurrentDir
= mStorageManager
.getFileByPath("/");
840 fillBlankRoot
= (mCurrentDir
!= null
);
843 if ((synchFolderRemotePath
!= null
&& mCurrentDir
!= null
&& (mCurrentDir
.getRemotePath().equals(synchFolderRemotePath
)))
846 mCurrentDir
= getStorageManager().getFileByPath(synchFolderRemotePath
);
847 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager()
848 .findFragmentById(R
.id
.fileList
);
849 if (fileListFragment
!= null
) {
850 fileListFragment
.listDirectory(mCurrentDir
);
854 setSupportProgressBarIndeterminateVisibility(inProgress
);
858 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncService
.SYNC_RESULT
);
859 if (synchResult
!= null
) {
860 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
861 mLastSslUntrustedServerResult
= synchResult
;
862 showDialog(DIALOG_SSL_VALIDATOR
);
869 private class UploadFinishReceiver
extends BroadcastReceiver
{
871 * Once the file upload has finished -> update view
872 * @author David A. Velasco
873 * {@link BroadcastReceiver} to enable upload feedback in UI
876 public void onReceive(Context context
, Intent intent
) {
877 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
878 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
879 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
880 boolean isDescendant
= (mCurrentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
881 if (sameAccount
&& isDescendant
) {
882 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
883 if (fileListFragment
!= null
) {
884 fileListFragment
.listDirectory();
893 * Once the file download has finished -> update view
895 private class DownloadFinishReceiver
extends BroadcastReceiver
{
897 public void onReceive(Context context
, Intent intent
) {
898 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
899 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
900 boolean sameAccount
= accountName
.equals(AccountUtils
.getCurrentOwnCloudAccount(context
).name
);
901 boolean isDescendant
= (mCurrentDir
!= null
) && (downloadedRemotePath
!= null
) && (downloadedRemotePath
.startsWith(mCurrentDir
.getRemotePath()));
902 if (sameAccount
&& isDescendant
) {
903 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
904 if (fileListFragment
!= null
) {
905 fileListFragment
.listDirectory();
918 public DataStorageManager
getStorageManager() {
919 return mStorageManager
;
927 public void onDirectoryClick(OCFile directory
) {
928 pushDirname(directory
);
929 ActionBar actionBar
= getSupportActionBar();
930 actionBar
.setDisplayHomeAsUpEnabled(true
);
933 // Resets the FileDetailsFragment on Tablets so that it always displays
934 FileDetailFragment fileDetails
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
935 if (fileDetails
!= null
&& !fileDetails
.isEmpty()) {
936 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
937 transaction
.remove(fileDetails
);
938 transaction
.add(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
);
939 transaction
.commit();
949 public void onFileClick(OCFile file
) {
951 // If we are on a large device -> update fragment
953 // 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'
954 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
955 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(file
, AccountUtils
.getCurrentOwnCloudAccount(this)), FileDetailFragment
.FTAG
);
956 transaction
.setTransition(FragmentTransaction
.TRANSIT_FRAGMENT_FADE
);
957 transaction
.commit();
959 } else { // small or medium screen device -> new Activity
960 Intent showDetailsIntent
= new Intent(this, FileDetailActivity
.class);
961 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_FILE
, file
);
962 showDetailsIntent
.putExtra(FileDetailFragment
.EXTRA_ACCOUNT
, AccountUtils
.getCurrentOwnCloudAccount(this));
963 startActivity(showDetailsIntent
);
972 public OCFile
getInitialDirectory() {
981 public void onFileStateChanged() {
982 OCFileListFragment fileListFragment
= (OCFileListFragment
) getSupportFragmentManager().findFragmentById(R
.id
.fileList
);
983 if (fileListFragment
!= null
) {
984 fileListFragment
.listDirectory();
993 public FileDownloaderBinder
getFileDownloaderBinder() {
994 return mDownloaderBinder
;
1002 public FileUploaderBinder
getFileUploaderBinder() {
1003 return mUploaderBinder
;
1007 /** Defines callbacks for service binding, passed to bindService() */
1008 private class ListServiceConnection
implements ServiceConnection
{
1011 public void onServiceConnected(ComponentName component
, IBinder service
) {
1012 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1013 Log
.d(TAG
, "Download service connected");
1014 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1015 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1016 Log
.d(TAG
, "Upload service connected");
1017 mUploaderBinder
= (FileUploaderBinder
) service
;
1021 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1022 if (mFileList
!= null
)
1023 mFileList
.listDirectory();
1025 FileDetailFragment fragment
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1026 if (fragment
!= null
)
1027 fragment
.updateFileDetails(false
);
1032 public void onServiceDisconnected(ComponentName component
) {
1033 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1034 Log
.d(TAG
, "Download service disconnected");
1035 mDownloaderBinder
= null
;
1036 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1037 Log
.d(TAG
, "Upload service disconnected");
1038 mUploaderBinder
= null
;
1046 * Launch an intent to request the PIN code to the user before letting him use the app
1048 private void requestPinCode() {
1049 boolean pinStart
= false
;
1050 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1051 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1053 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1054 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1061 public void onSavedCertificate() {
1062 startSynchronization();
1067 public void onFailedSavingCertificate() {
1068 showDialog(DIALOG_CERT_NOT_SAVED
);
1073 * Updates the view associated to the activity after the finish of some operation over files
1074 * in the current account.
1076 * @param operation Removal operation performed.
1077 * @param result Result of the removal.
1080 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1081 if (operation
instanceof RemoveFileOperation
) {
1082 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1084 } else if (operation
instanceof RenameFileOperation
) {
1085 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1090 * Updates the view associated to the activity after the finish of an operation trying to remove a
1093 * @param operation Removal operation performed.
1094 * @param result Result of the removal.
1096 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1097 dismissDialog(DIALOG_SHORT_WAIT
);
1098 if (result
.isSuccess()) {
1099 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1101 OCFile removedFile
= operation
.getFile();
1103 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1104 if (details
!= null
&& removedFile
.equals(details
.getDisplayedFile()) ) {
1105 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
1106 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1107 transaction
.commit();
1110 if (mStorageManager
.getFileById(removedFile
.getParentId()).equals(mCurrentDir
)) {
1111 mFileList
.listDirectory();
1115 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1117 if (result
.isSslRecoverableException()) {
1118 mLastSslUntrustedServerResult
= result
;
1119 showDialog(DIALOG_SSL_VALIDATOR
);
1125 * Updates the view associated to the activity after the finish of an operation trying to rename a
1128 * @param operation Renaming operation performed.
1129 * @param result Result of the renaming.
1131 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1132 dismissDialog(DIALOG_SHORT_WAIT
);
1133 OCFile renamedFile
= operation
.getFile();
1134 if (result
.isSuccess()) {
1136 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1137 if (details
!= null
&& renamedFile
.equals(details
.getDisplayedFile()) ) {
1138 details
.updateFileDetails(renamedFile
, AccountUtils
.getCurrentOwnCloudAccount(this));
1141 if (mStorageManager
.getFileById(renamedFile
.getParentId()).equals(mCurrentDir
)) {
1142 mFileList
.listDirectory();
1146 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1147 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1149 // TODO throw again the new rename dialog
1151 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1153 if (result
.isSslRecoverableException()) {
1154 mLastSslUntrustedServerResult
= result
;
1155 showDialog(DIALOG_SSL_VALIDATOR
);
1166 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1167 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1168 if (fileListFragment != null) {
1169 fileListFragment.listDirectory();
1172 FileDetailFragment details
= (FileDetailFragment
) getSupportFragmentManager().findFragmentByTag(FileDetailFragment
.FTAG
);
1173 if (details
!= null
&& file
.equals(details
.getDisplayedFile()) ) {
1174 if (downloading
|| uploading
) {
1175 details
.updateFileDetails(file
, AccountUtils
.getCurrentOwnCloudAccount(this));
1177 details
.updateFileDetails(downloading
|| uploading
);