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 version 2,
7 * as published by the Free Software Foundation.
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
.Dialog
;
26 import android
.app
.ProgressDialog
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.ComponentName
;
29 import android
.content
.ContentResolver
;
30 import android
.content
.Context
;
31 import android
.content
.DialogInterface
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.content
.SyncRequest
;
37 import android
.content
.res
.Resources
.NotFoundException
;
38 import android
.database
.Cursor
;
39 import android
.net
.Uri
;
40 import android
.os
.Bundle
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.provider
.MediaStore
;
44 import android
.support
.v4
.app
.Fragment
;
45 import android
.support
.v4
.app
.FragmentManager
;
46 import android
.support
.v4
.app
.FragmentTransaction
;
47 import android
.support
.v4
.content
.LocalBroadcastManager
;
48 import android
.util
.Log
;
49 import android
.view
.View
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ArrayAdapter
;
52 import android
.widget
.TextView
;
53 import android
.widget
.Toast
;
55 import com
.actionbarsherlock
.app
.ActionBar
;
56 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
57 import com
.actionbarsherlock
.view
.Menu
;
58 import com
.actionbarsherlock
.view
.MenuInflater
;
59 import com
.actionbarsherlock
.view
.MenuItem
;
60 import com
.actionbarsherlock
.view
.Window
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileObserverService
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
71 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
72 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
73 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
.ResultCode
;
74 import com
.owncloud
.android
.operations
.CreateShareOperation
;
75 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
76 import com
.owncloud
.android
.operations
.RenameFileOperation
;
77 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
78 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
79 import com
.owncloud
.android
.services
.OperationsService
;
80 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
81 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
82 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
83 import com
.owncloud
.android
.ui
.dialog
.LoadingDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
86 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
87 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
88 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
89 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
92 import com
.owncloud
.android
.utils
.DisplayUtils
;
93 import com
.owncloud
.android
.utils
.Log_OC
;
97 * Displays, what files the user has available in his ownCloud.
99 * @author Bartek Przybylski
100 * @author David A. Velasco
103 public class FileDisplayActivity
extends FileActivity
implements
104 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, EditNameDialogListener
{
106 private ArrayAdapter
<String
> mDirectories
;
108 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
109 private UploadFinishReceiver mUploadFinishReceiver
;
110 private DownloadFinishReceiver mDownloadFinishReceiver
;
111 private OperationsServiceReceiver mOperationsServiceReceiver
;
112 private FileDownloaderBinder mDownloaderBinder
= null
;
113 private FileUploaderBinder mUploaderBinder
= null
;
114 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
115 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
117 private boolean mDualPane
;
118 private View mLeftFragmentContainer
;
119 private View mRightFragmentContainer
;
121 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
122 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
123 private static final String KEY_REFRESH_SHARES_IN_PROGRESS
= "SHARES_IN_PROGRESS";
125 public static final int DIALOG_SHORT_WAIT
= 0;
126 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
127 private static final int DIALOG_SSL_VALIDATOR
= 2;
128 private static final int DIALOG_CERT_NOT_SAVED
= 3;
130 private static final String DIALOG_WAIT_TAG
= "DIALOG_WAIT";
132 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
134 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
135 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
137 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
139 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
140 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
142 private OCFile mWaitingToPreview
;
144 private boolean mSyncInProgress
= false
;
145 private boolean mRefreshSharesInProgress
= false
;
148 protected void onCreate(Bundle savedInstanceState
) {
149 Log_OC
.d(TAG
, "onCreate() start");
150 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
152 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
154 /// bindings to transference services
155 mUploadConnection
= new ListServiceConnection();
156 mDownloadConnection
= new ListServiceConnection();
157 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
158 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
160 // PIN CODE request ; best location is to decide, let's try this first
161 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
163 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
168 Intent observer_intent
= new Intent(this, FileObserverService
.class);
169 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
170 startService(observer_intent
);
172 /// Load of saved instance state
173 if(savedInstanceState
!= null
) {
174 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mRefreshSharesInProgress
= savedInstanceState
.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mRefreshSharesInProgress
= false
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
188 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
189 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
190 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
191 if (savedInstanceState
== null
) {
192 createMinFragments();
196 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
197 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
198 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
|| mRefreshSharesInProgress
); // always AFTER setContentView(...) ; to work around bug in its implementation
200 Log_OC
.d(TAG
, "onCreate() end");
204 protected void onStart() {
206 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
210 protected void onDestroy() {
212 if (mDownloadConnection
!= null
)
213 unbindService(mDownloadConnection
);
214 if (mUploadConnection
!= null
)
215 unbindService(mUploadConnection
);
220 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
223 protected void onAccountSet(boolean stateWasRecovered
) {
224 super.onAccountSet(stateWasRecovered
);
225 if (getAccount() != null
) {
226 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
227 OCFile file
= getFile();
228 // get parent from path
229 String parentPath
= "";
231 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
232 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
233 // get parent from path
234 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
235 if (getStorageManager().getFileByPath(parentPath
) == null
)
236 file
= null
; // not able to know the directory where the file is uploading
238 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
242 // fall back to root folder
243 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
246 setNavigationListWithFolder(file
);
248 if (!stateWasRecovered
) {
249 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
250 initFragmentsWithFile();
251 if (file
.isFolder()) {
252 startSyncFolderOperation(file
);
256 updateFragmentsVisibility(!file
.isFolder());
257 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
263 private void setNavigationListWithFolder(OCFile file
) {
264 mDirectories
.clear();
265 OCFile fileIt
= file
;
267 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
268 if (fileIt
.isFolder()) {
269 mDirectories
.add(fileIt
.getFileName());
271 // get parent from path
272 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
273 fileIt
= getStorageManager().getFileByPath(parentPath
);
275 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
279 private void createMinFragments() {
280 OCFileListFragment listOfFiles
= new OCFileListFragment();
281 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
282 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
283 transaction
.commit();
286 private void initFragmentsWithFile() {
287 if (getAccount() != null
&& getFile() != null
) {
289 OCFileListFragment listOfFiles
= getListOfFilesFragment();
290 if (listOfFiles
!= null
) {
291 listOfFiles
.listDirectory(getCurrentDir());
293 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
297 OCFile file
= getFile();
298 Fragment secondFragment
= chooseInitialSecondFragment(file
);
299 if (secondFragment
!= null
) {
300 setSecondFragment(secondFragment
);
301 updateFragmentsVisibility(true
);
302 updateNavigationElementsInActionBar(file
);
305 cleanSecondFragment();
309 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
310 if (getAccount() == null
) {
311 Log
.wtf(TAG
, "\t account is NULL");
313 if (getFile() == null
) {
314 Log
.wtf(TAG
, "\t file is NULL");
319 private Fragment
chooseInitialSecondFragment(OCFile file
) {
320 Fragment secondFragment
= null
;
321 if (file
!= null
&& !file
.isFolder()) {
322 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
323 && file
.getLastSyncDateForProperties() > 0 // temporal fix
325 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
326 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
327 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
330 secondFragment
= new FileDetailFragment(file
, getAccount());
333 return secondFragment
;
338 * Replaces the second fragment managed by the activity with the received as
341 * Assumes never will be more than two fragments managed at the same time.
343 * @param fragment New second Fragment to set.
345 private void setSecondFragment(Fragment fragment
) {
346 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
347 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
348 transaction
.commit();
352 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
354 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
355 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
357 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
361 } else if (existsSecondFragment
) {
362 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
363 mLeftFragmentContainer
.setVisibility(View
.GONE
);
365 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
370 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
374 mRightFragmentContainer
.setVisibility(View
.GONE
);
380 private OCFileListFragment
getListOfFilesFragment() {
381 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
382 if (listOfFiles
!= null
) {
383 return (OCFileListFragment
)listOfFiles
;
385 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
389 protected FileFragment
getSecondFragment() {
390 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
391 if (second
!= null
) {
392 return (FileFragment
)second
;
397 public void cleanSecondFragment() {
398 Fragment second
= getSecondFragment();
399 if (second
!= null
) {
400 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
404 updateFragmentsVisibility(false
);
405 updateNavigationElementsInActionBar(null
);
408 protected void refeshListOfFilesFragment() {
409 OCFileListFragment fileListFragment
= getListOfFilesFragment();
410 if (fileListFragment
!= null
) {
411 fileListFragment
.listDirectory();
415 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
416 FileFragment secondFragment
= getSecondFragment();
417 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
418 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
419 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
420 OCFile fileInFragment
= detailsFragment
.getFile();
421 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
422 // the user browsed to other file ; forget the automatic preview
423 mWaitingToPreview
= null
;
425 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
426 // grant that the right panel updates the progress bar
427 detailsFragment
.listenForTransferProgress();
428 detailsFragment
.updateFileDetails(true
, false
);
430 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
431 // update the right panel
432 boolean detailsFragmentChanged
= false
;
435 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
436 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
437 startMediaPreview(mWaitingToPreview
, 0, true
);
438 detailsFragmentChanged
= true
;
440 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
443 mWaitingToPreview
= null
;
445 if (!detailsFragmentChanged
) {
446 detailsFragment
.updateFileDetails(false
, (success
));
453 public boolean onCreateOptionsMenu(Menu menu
) {
454 MenuInflater inflater
= getSherlock().getMenuInflater();
455 inflater
.inflate(R
.menu
.main_menu
, menu
);
460 public boolean onOptionsItemSelected(MenuItem item
) {
461 boolean retval
= true
;
462 switch (item
.getItemId()) {
463 case R
.id
.action_create_dir
: {
464 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
465 dialog
.show(getSupportFragmentManager(), "createdirdialog");
468 case R
.id
.action_sync_account
: {
469 startSynchronization();
472 case R
.id
.action_upload
: {
473 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
476 case R
.id
.action_settings
: {
477 Intent settingsIntent
= new Intent(this, Preferences
.class);
478 startActivity(settingsIntent
);
481 case android
.R
.id
.home
: {
482 FileFragment second
= getSecondFragment();
483 OCFile currentDir
= getCurrentDir();
484 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
485 (second
!= null
&& second
.getFile() != null
)) {
492 retval
= super.onOptionsItemSelected(item
);
497 private void startSynchronization() {
498 Log_OC
.e(TAG
, "Got to start sync");
499 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
500 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
501 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
502 Bundle bundle
= new Bundle();
503 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
504 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
505 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
506 ContentResolver
.requestSync(
508 MainApp
.getAuthority(), bundle
);
510 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
511 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
512 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
513 builder
.setExpedited(true
);
514 builder
.setManual(true
);
516 SyncRequest request
= builder
.build();
517 ContentResolver
.requestSync(request
);
523 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
524 if (itemPosition
!= 0) {
525 String targetPath
= "";
526 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
527 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
529 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
530 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
531 if (targetFolder
!= null
) {
532 browseTo(targetFolder
);
535 // the next operation triggers a new call to this method, but it's necessary to
536 // ensure that the name exposed in the action bar is the current directory when the
537 // user selected it in the navigation list
538 getSupportActionBar().setSelectedNavigationItem(0);
544 * Called, when the user selected something for uploading
546 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
547 super.onActivityResult(requestCode
, resultCode
, data
);
549 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
550 requestSimpleUpload(data
, resultCode
);
552 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
553 requestMultipleUpload(data
, resultCode
);
558 private void requestMultipleUpload(Intent data
, int resultCode
) {
559 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
560 if (filePaths
!= null
) {
561 String
[] remotePaths
= new String
[filePaths
.length
];
562 String remotePathBase
= "";
563 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
564 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
566 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
567 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
568 for (int j
= 0; j
< remotePaths
.length
; j
++) {
569 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
572 Intent i
= new Intent(this, FileUploader
.class);
573 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
574 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
575 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
576 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
577 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
578 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
582 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
583 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
590 private void requestSimpleUpload(Intent data
, int resultCode
) {
591 String filepath
= null
;
593 Uri selectedImageUri
= data
.getData();
595 String filemanagerstring
= selectedImageUri
.getPath();
596 String selectedImagePath
= getPath(selectedImageUri
);
598 if (selectedImagePath
!= null
)
599 filepath
= selectedImagePath
;
601 filepath
= filemanagerstring
;
603 } catch (Exception e
) {
604 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
608 if (filepath
== null
) {
609 Log_OC
.e(TAG
, "Couldnt resolve path to file");
610 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
616 Intent i
= new Intent(this, FileUploader
.class);
617 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
619 String remotepath
= new String();
620 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
621 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
623 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
624 remotepath
+= OCFile
.PATH_SEPARATOR
;
625 remotepath
+= new File(filepath
).getName();
627 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
628 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
629 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
630 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
631 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
636 public void onBackPressed() {
637 OCFileListFragment listOfFiles
= getListOfFilesFragment();
638 if (mDualPane
|| getSecondFragment() == null
) {
639 if (listOfFiles
!= null
) { // should never be null, indeed
640 if (mDirectories
.getCount() <= 1) {
644 int levelsUp
= listOfFiles
.onBrowseUp();
645 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
650 if (listOfFiles
!= null
) { // should never be null, indeed
651 setFile(listOfFiles
.getCurrentFile());
653 cleanSecondFragment();
658 protected void onSaveInstanceState(Bundle outState
) {
659 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
660 Log_OC
.e(TAG
, "onSaveInstanceState() start");
661 super.onSaveInstanceState(outState
);
662 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
663 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
664 outState
.putBoolean(FileDisplayActivity
.KEY_REFRESH_SHARES_IN_PROGRESS
, mRefreshSharesInProgress
);
666 Log_OC
.d(TAG
, "onSaveInstanceState() end");
672 protected void onResume() {
674 Log_OC
.e(TAG
, "onResume() start");
676 // Listen for sync messages
677 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
678 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
679 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FOLDER_SIZE_SYNCED
);
680 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FOLDER_CONTENTS_SYNCED
);
681 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SYNCED
);
682 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
683 //registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
684 LocalBroadcastManager
.getInstance(this).registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
686 // Listen for upload messages
687 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
688 mUploadFinishReceiver
= new UploadFinishReceiver();
689 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
691 // Listen for download messages
692 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
693 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
694 mDownloadFinishReceiver
= new DownloadFinishReceiver();
695 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
697 // Listen for messages from the OperationsService
698 IntentFilter operationsIntentFilter
= new IntentFilter(OperationsService
.ACTION_OPERATION_ADDED
);
699 operationsIntentFilter
.addAction(OperationsService
.ACTION_OPERATION_FINISHED
);
700 mOperationsServiceReceiver
= new OperationsServiceReceiver();
701 LocalBroadcastManager
.getInstance(this).registerReceiver(mOperationsServiceReceiver
, operationsIntentFilter
);
703 Log_OC
.d(TAG
, "onResume() end");
708 protected void onPause() {
710 Log_OC
.e(TAG
, "onPause() start");
711 if (mSyncBroadcastReceiver
!= null
) {
712 //unregisterReceiver(mSyncBroadcastReceiver);
713 LocalBroadcastManager
.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver
);
714 mSyncBroadcastReceiver
= null
;
716 if (mUploadFinishReceiver
!= null
) {
717 unregisterReceiver(mUploadFinishReceiver
);
718 mUploadFinishReceiver
= null
;
720 if (mDownloadFinishReceiver
!= null
) {
721 unregisterReceiver(mDownloadFinishReceiver
);
722 mDownloadFinishReceiver
= null
;
724 if (mOperationsServiceReceiver
!= null
) {
725 LocalBroadcastManager
.getInstance(this).unregisterReceiver(mOperationsServiceReceiver
);
726 mOperationsServiceReceiver
= null
;
728 Log_OC
.d(TAG
, "onPause() end");
733 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
734 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
735 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
741 protected Dialog
onCreateDialog(int id
) {
742 Dialog dialog
= null
;
743 AlertDialog
.Builder builder
;
745 case DIALOG_SHORT_WAIT
: {
746 ProgressDialog working_dialog
= new ProgressDialog(this);
747 working_dialog
.setMessage(getResources().getString(
748 R
.string
.wait_a_moment
));
749 working_dialog
.setIndeterminate(true
);
750 working_dialog
.setCancelable(false
);
751 dialog
= working_dialog
;
754 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
756 String
[] items
= null
;
758 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
759 getString(R
.string
.actionbar_upload_from_apps
),
760 getString(R
.string
.actionbar_failed_instant_upload
) };
762 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
763 getString(R
.string
.actionbar_upload_from_apps
) };
765 if (InstantUploadActivity
.IS_ENABLED
)
770 builder
= new AlertDialog
.Builder(this);
771 builder
.setTitle(R
.string
.actionbar_upload
);
772 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
773 public void onClick(DialogInterface dialog
, int item
) {
776 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
777 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
778 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
780 // TODO create and handle new fragment
781 // LocalFileListFragment
783 } else if (item
== 1) {
784 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
785 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
786 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
787 ACTION_SELECT_CONTENT_FROM_APPS
);
788 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
789 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
790 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
791 startActivity(action
);
795 dialog
= builder
.create();
798 case DIALOG_SSL_VALIDATOR
: {
799 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
802 case DIALOG_CERT_NOT_SAVED
: {
803 builder
= new AlertDialog
.Builder(this);
804 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
805 builder
.setCancelable(false
);
806 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
808 public void onClick(DialogInterface dialog
, int which
) {
812 dialog
= builder
.create();
824 * Show loading dialog
826 public void showLoadingDialog() {
828 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
829 FragmentManager fm
= getSupportFragmentManager();
830 FragmentTransaction ft
= fm
.beginTransaction();
831 loading
.show(ft
, DIALOG_WAIT_TAG
);
836 * Dismiss loading dialog
838 public void dismissLoadingDialog(){
839 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
841 LoadingDialog loading
= (LoadingDialog
) frag
;
848 * Translates a content URI of an image to a physical path
850 * @param uri The URI to resolve
851 * @return The path to the image or null if it could not be found
853 public String
getPath(Uri uri
) {
854 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
855 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
856 if (cursor
!= null
) {
857 int column_index
= cursor
858 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
859 cursor
.moveToFirst();
860 return cursor
.getString(column_index
);
866 * Pushes a directory to the drop down list
867 * @param directory to push
868 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
870 public void pushDirname(OCFile directory
) {
871 if(!directory
.isFolder()){
872 throw new IllegalArgumentException("Only directories may be pushed!");
874 mDirectories
.insert(directory
.getFileName(), 0);
879 * Pops a directory name from the drop down list
880 * @return True, unless the stack is empty
882 public boolean popDirname() {
883 mDirectories
.remove(mDirectories
.getItem(0));
884 return !mDirectories
.isEmpty();
887 // Custom array adapter to override text colors
888 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
890 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
894 public View
getView(int position
, View convertView
, ViewGroup parent
) {
895 View v
= super.getView(position
, convertView
, parent
);
897 ((TextView
) v
).setTextColor(getResources().getColorStateList(
898 android
.R
.color
.white
));
902 public View
getDropDownView(int position
, View convertView
,
904 View v
= super.getDropDownView(position
, convertView
, parent
);
906 ((TextView
) v
).setTextColor(getResources().getColorStateList(
907 android
.R
.color
.white
));
914 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
917 * {@link BroadcastReceiver} to enable syncing feedback in UI
920 public void onReceive(Context context
, Intent intent
) {
921 String event
= intent
.getAction();
922 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
923 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
924 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
925 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
929 if (!FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
930 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
931 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
933 if (currentDir
== null
) {
934 // current folder was removed from the server
935 Toast
.makeText( FileDisplayActivity
.this,
936 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
942 if (currentFile
== null
&& !getFile().isFolder()) {
943 // currently selected file was removed in the server, and now we know it
944 cleanSecondFragment();
945 currentFile
= currentDir
;
948 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
949 OCFileListFragment fileListFragment
= getListOfFilesFragment();
950 if (fileListFragment
!= null
) {
951 fileListFragment
.listDirectory(currentDir
);
954 setFile(currentFile
);
957 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
958 !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SYNCED
.equals(event
) &&
959 (synchResult
== null
|| synchResult
.isSuccess())) ;
961 if (synchResult
!= null
&&
962 synchResult
.isSuccess() &&
963 (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SYNCED
.equals(event
) ||
964 FileSyncAdapter
.EVENT_FOLDER_CONTENTS_SYNCED
.equals(event
)
966 !mRefreshSharesInProgress
&&
967 getFileOperationsHelper().isSharedSupported(FileDisplayActivity
.this)
973 //removeStickyBroadcast(intent);
974 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
|| mRefreshSharesInProgress
);
977 if (synchResult
!= null
) {
978 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
979 mLastSslUntrustedServerResult
= synchResult
;
980 showDialog(DIALOG_SSL_VALIDATOR
);
987 private class UploadFinishReceiver
extends BroadcastReceiver
{
989 * Once the file upload has finished -> update view
990 * @author David A. Velasco
991 * {@link BroadcastReceiver} to enable upload feedback in UI
994 public void onReceive(Context context
, Intent intent
) {
995 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
996 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
997 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
998 OCFile currentDir
= getCurrentDir();
999 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1000 if (sameAccount
&& isDescendant
) {
1001 refeshListOfFilesFragment();
1009 * Class waiting for broadcast events from the {@link FielDownloader} service.
1011 * Updates the UI when a download is started or finished, provided that it is relevant for the
1014 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1016 public void onReceive(Context context
, Intent intent
) {
1017 boolean sameAccount
= isSameAccount(context
, intent
);
1018 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1019 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1021 if (sameAccount
&& isDescendant
) {
1022 refeshListOfFilesFragment();
1023 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1026 removeStickyBroadcast(intent
);
1029 private boolean isDescendant(String downloadedRemotePath
) {
1030 OCFile currentDir
= getCurrentDir();
1031 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1034 private boolean isSameAccount(Context context
, Intent intent
) {
1035 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1036 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1042 * Class waiting for broadcast events from the {@link OperationsService}.
1044 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1045 * operation performed in {@link OperationsService}.
1047 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1048 * probably all the operations associated to the app model.
1050 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1053 public void onReceive(Context context
, Intent intent
) {
1054 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1056 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1057 mRefreshSharesInProgress
= false
;
1059 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1060 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1061 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1062 && getStorageManager() != null
1064 refeshListOfFilesFragment();
1066 if ((getSharesResult
!= null
) &&
1067 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1068 mLastSslUntrustedServerResult
= getSharesResult
;
1069 showDialog(DIALOG_SSL_VALIDATOR
);
1072 setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress
|| mSyncInProgress
);
1079 public void browseToRoot() {
1080 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1081 if (listOfFiles
!= null
) { // should never be null, indeed
1082 while (mDirectories
.getCount() > 1) {
1085 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1086 listOfFiles
.listDirectory(root
);
1087 setFile(listOfFiles
.getCurrentFile());
1088 startSyncFolderOperation(root
);
1090 cleanSecondFragment();
1094 public void browseTo(OCFile folder
) {
1095 if (folder
== null
|| !folder
.isFolder()) {
1096 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1098 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1099 if (listOfFiles
!= null
) {
1100 setNavigationListWithFolder(folder
);
1101 listOfFiles
.listDirectory(folder
);
1102 setFile(listOfFiles
.getCurrentFile());
1103 startSyncFolderOperation(folder
);
1105 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1107 cleanSecondFragment();
1114 * Updates action bar and second fragment, if in dual pane mode.
1117 public void onBrowsedDownTo(OCFile directory
) {
1118 pushDirname(directory
);
1119 cleanSecondFragment();
1122 startSyncFolderOperation(directory
);
1127 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1129 * @param file Image {@link OCFile} to show.
1132 public void startImagePreview(OCFile file
) {
1133 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1134 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1135 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1136 startActivity(showDetailsIntent
);
1140 * Stars the preview of an already down media {@link OCFile}.
1142 * @param file Media {@link OCFile} to preview.
1143 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1144 * @param autoplay When 'true', the playback will start without user interactions.
1147 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1148 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1149 setSecondFragment(mediaFragment
);
1150 updateFragmentsVisibility(true
);
1151 updateNavigationElementsInActionBar(file
);
1156 * Requests the download of the received {@link OCFile} , updates the UI
1157 * to monitor the download progress and prepares the activity to preview
1158 * or open the file when the download finishes.
1160 * @param file {@link OCFile} to download and preview.
1163 public void startDownloadForPreview(OCFile file
) {
1164 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1165 setSecondFragment(detailFragment
);
1166 mWaitingToPreview
= file
;
1167 requestForDownload();
1168 updateFragmentsVisibility(true
);
1169 updateNavigationElementsInActionBar(file
);
1175 * Shows the information of the {@link OCFile} received as a
1176 * parameter in the second fragment.
1178 * @param file {@link OCFile} whose details will be shown
1181 public void showDetails(OCFile file
) {
1182 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1183 setSecondFragment(detailFragment
);
1184 updateFragmentsVisibility(true
);
1185 updateNavigationElementsInActionBar(file
);
1193 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1194 ActionBar actionBar
= getSupportActionBar();
1195 if (chosenFile
== null
|| mDualPane
) {
1196 // only list of files - set for browsing through folders
1197 OCFile currentDir
= getCurrentDir();
1198 actionBar
.setDisplayHomeAsUpEnabled(currentDir
!= null
&& currentDir
.getParentId() != 0);
1199 actionBar
.setDisplayShowTitleEnabled(false
);
1200 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
1201 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1204 actionBar
.setDisplayHomeAsUpEnabled(true
);
1205 actionBar
.setDisplayShowTitleEnabled(true
);
1206 actionBar
.setTitle(chosenFile
.getFileName());
1207 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1216 public void onFileStateChanged() {
1217 refeshListOfFilesFragment();
1218 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1226 public FileDownloaderBinder
getFileDownloaderBinder() {
1227 return mDownloaderBinder
;
1235 public FileUploaderBinder
getFileUploaderBinder() {
1236 return mUploaderBinder
;
1240 /** Defines callbacks for service binding, passed to bindService() */
1241 private class ListServiceConnection
implements ServiceConnection
{
1244 public void onServiceConnected(ComponentName component
, IBinder service
) {
1245 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1246 Log_OC
.d(TAG
, "Download service connected");
1247 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1248 if (mWaitingToPreview
!= null
) {
1249 requestForDownload();
1252 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1253 Log_OC
.d(TAG
, "Upload service connected");
1254 mUploaderBinder
= (FileUploaderBinder
) service
;
1258 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1259 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1260 if (listOfFiles
!= null
) {
1261 listOfFiles
.listDirectory();
1263 FileFragment secondFragment
= getSecondFragment();
1264 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1265 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1266 detailFragment
.listenForTransferProgress();
1267 detailFragment
.updateFileDetails(false
, false
);
1272 public void onServiceDisconnected(ComponentName component
) {
1273 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1274 Log_OC
.d(TAG
, "Download service disconnected");
1275 mDownloaderBinder
= null
;
1276 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1277 Log_OC
.d(TAG
, "Upload service disconnected");
1278 mUploaderBinder
= null
;
1286 * Launch an intent to request the PIN code to the user before letting him use the app
1288 private void requestPinCode() {
1289 boolean pinStart
= false
;
1290 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1291 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1293 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1294 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1301 public void onSavedCertificate() {
1302 startSyncFolderOperation(getCurrentDir());
1307 public void onFailedSavingCertificate() {
1308 showDialog(DIALOG_CERT_NOT_SAVED
);
1313 * Updates the view associated to the activity after the finish of some operation over files
1314 * in the current account.
1316 * @param operation Removal operation performed.
1317 * @param result Result of the removal.
1320 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1321 if (operation
instanceof RemoveFileOperation
) {
1322 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1324 } else if (operation
instanceof RenameFileOperation
) {
1325 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1327 } else if (operation
instanceof SynchronizeFileOperation
) {
1328 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1330 } else if (operation
instanceof CreateFolderOperation
) {
1331 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1333 } else if (operation
instanceof CreateShareOperation
) {
1334 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1340 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1341 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
1343 Toast t
= Toast
.makeText(this, getString(R
.string
.share_link_file_no_exist
), Toast
.LENGTH_LONG
);
1346 } else if (result
.isSuccess()) {
1347 refeshListOfFilesFragment();
1349 Intent sendIntent
= operation
.getSendIntent();
1350 startActivity(sendIntent
);
1356 * Updates the view associated to the activity after the finish of an operation trying to remove a
1359 * @param operation Removal operation performed.
1360 * @param result Result of the removal.
1362 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1363 dismissLoadingDialog();
1364 if (result
.isSuccess()) {
1365 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1367 OCFile removedFile
= operation
.getFile();
1368 getSecondFragment();
1369 FileFragment second
= getSecondFragment();
1370 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1371 cleanSecondFragment();
1373 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1374 refeshListOfFilesFragment();
1378 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1380 if (result
.isSslRecoverableException()) {
1381 mLastSslUntrustedServerResult
= result
;
1382 showDialog(DIALOG_SSL_VALIDATOR
);
1388 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1390 * @param operation Creation operation performed.
1391 * @param result Result of the creation.
1393 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1394 if (result
.isSuccess()) {
1395 dismissLoadingDialog();
1396 refeshListOfFilesFragment();
1399 dismissLoadingDialog();
1400 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1401 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1404 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1407 } catch (NotFoundException e
) {
1408 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1416 * Updates the view associated to the activity after the finish of an operation trying to rename a
1419 * @param operation Renaming operation performed.
1420 * @param result Result of the renaming.
1422 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1423 dismissLoadingDialog();
1424 OCFile renamedFile
= operation
.getFile();
1425 if (result
.isSuccess()) {
1427 FileFragment details
= getSecondFragment();
1428 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1429 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1432 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1433 refeshListOfFilesFragment();
1437 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1438 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1440 // TODO throw again the new rename dialog
1441 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1442 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1445 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1447 if (result
.isSslRecoverableException()) {
1448 mLastSslUntrustedServerResult
= result
;
1449 showDialog(DIALOG_SSL_VALIDATOR
);
1456 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1457 dismissLoadingDialog();
1458 OCFile syncedFile
= operation
.getLocalFile();
1459 if (!result
.isSuccess()) {
1460 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1461 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1462 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1463 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1469 if (operation
.transferWasRequested()) {
1470 refeshListOfFilesFragment();
1471 onTransferStateChanged(syncedFile
, true
, true
);
1474 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1485 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1487 FileFragment details
= getSecondFragment();
1488 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1489 if (downloading
|| uploading
) {
1490 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1492 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1499 public void onDismiss(EditNameDialog dialog
) {
1500 if (dialog
.getResult()) {
1501 String newDirectoryName
= dialog
.getNewFilename().trim();
1502 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1503 if (newDirectoryName
.length() > 0) {
1504 String path
= getCurrentDir().getRemotePath();
1507 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1508 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1509 operation
.execute( getAccount(),
1510 FileDisplayActivity
.this,
1511 FileDisplayActivity
.this,
1513 FileDisplayActivity
.this);
1515 showLoadingDialog();
1521 private void requestForDownload() {
1522 Account account
= getAccount();
1523 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1524 Intent i
= new Intent(this, FileDownloader
.class);
1525 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1526 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1532 private OCFile
getCurrentDir() {
1533 OCFile file
= getFile();
1535 if (file
.isFolder()) {
1537 } else if (getStorageManager() != null
) {
1538 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1539 return getStorageManager().getFileByPath(parentPath
);
1545 public void startSyncFolderOperation(OCFile folder
) {
1546 long currentSyncTime
= System
.currentTimeMillis();
1548 mSyncInProgress
= true
;
1550 // perform folder synchronization
1551 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1554 getStorageManager(),
1556 getApplicationContext()
1558 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1560 setSupportProgressBarIndeterminateVisibility(true
);
1564 private void startGetShares() {
1565 // Get shared files/folders
1566 Intent intent
= new Intent(this, OperationsService
.class);
1567 intent
.putExtra(OperationsService
.EXTRA_ACCOUNT
, getAccount());
1568 startService(intent
);
1570 mRefreshSharesInProgress
= true
;