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
;
22 import android
.accounts
.Account
;
23 import android
.app
.AlertDialog
;
24 import android
.app
.Dialog
;
25 import android
.app
.ProgressDialog
;
26 import android
.content
.BroadcastReceiver
;
27 import android
.content
.ComponentName
;
28 import android
.content
.ContentResolver
;
29 import android
.content
.Context
;
30 import android
.content
.DialogInterface
;
31 import android
.content
.Intent
;
32 import android
.content
.IntentFilter
;
33 import android
.content
.ServiceConnection
;
34 import android
.content
.SharedPreferences
;
35 import android
.content
.SyncRequest
;
36 import android
.content
.res
.Resources
.NotFoundException
;
37 import android
.database
.Cursor
;
38 import android
.net
.Uri
;
39 import android
.os
.Bundle
;
40 import android
.os
.IBinder
;
41 import android
.preference
.PreferenceManager
;
42 import android
.provider
.MediaStore
;
43 import android
.support
.v4
.app
.Fragment
;
44 import android
.support
.v4
.app
.FragmentManager
;
45 import android
.support
.v4
.app
.FragmentTransaction
;
46 //import android.support.v4.content.LocalBroadcastManager;
47 import android
.util
.Log
;
48 import android
.view
.View
;
49 import android
.view
.ViewGroup
;
50 import android
.widget
.ArrayAdapter
;
51 import android
.widget
.TextView
;
52 import android
.widget
.Toast
;
54 import com
.actionbarsherlock
.app
.ActionBar
;
55 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
56 import com
.actionbarsherlock
.view
.Menu
;
57 import com
.actionbarsherlock
.view
.MenuInflater
;
58 import com
.actionbarsherlock
.view
.MenuItem
;
59 import com
.actionbarsherlock
.view
.Window
;
60 import com
.owncloud
.android
.MainApp
;
61 import com
.owncloud
.android
.R
;
62 import com
.owncloud
.android
.datamodel
.OCFile
;
63 import com
.owncloud
.android
.files
.services
.FileDownloader
;
64 import com
.owncloud
.android
.files
.services
.FileObserverService
;
65 import com
.owncloud
.android
.files
.services
.FileUploader
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
68 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
70 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
73 import com
.owncloud
.android
.lib
.common
.operations
.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
.operations
.UnshareLinkOperation
;
80 import com
.owncloud
.android
.services
.OperationsService
;
81 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
82 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
83 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
85 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
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 HookActivity
implements
104 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
, 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";
124 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
126 public static final int DIALOG_SHORT_WAIT
= 0;
127 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
128 //private static final int DIALOG_SSL_VALIDATOR = 2;
129 private static final int DIALOG_CERT_NOT_SAVED
= 2;
131 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
133 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
134 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
136 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
138 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
139 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
141 private OCFile mWaitingToPreview
;
143 private boolean mSyncInProgress
= false
;
144 //private boolean mRefreshSharesInProgress = false;
146 private String DIALOG_UNTRUSTED_CERT
;
148 private OCFile mWaitingToSend
;
151 protected void onCreate(Bundle savedInstanceState
) {
152 Log_OC
.d(TAG
, "onCreate() start");
153 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
155 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
157 /// bindings to transference services
158 mUploadConnection
= new ListServiceConnection();
159 mDownloadConnection
= new ListServiceConnection();
160 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
161 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
163 // PIN CODE request ; best location is to decide, let's try this first
164 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
166 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
171 Intent observer_intent
= new Intent(this, FileObserverService
.class);
172 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
173 startService(observer_intent
);
175 /// Load of saved instance state
176 if(savedInstanceState
!= null
) {
177 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
178 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
179 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
180 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
183 mWaitingToPreview
= null
;
184 mSyncInProgress
= false
;
185 //mRefreshSharesInProgress = false;
186 mWaitingToSend
= null
;
191 // Inflate and set the layout view
192 setContentView(R
.layout
.files
);
193 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
194 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
195 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
196 if (savedInstanceState
== null
) {
197 createMinFragments();
199 Log_OC
.d(TAG
, "Init the secondFragment again");
201 initFragmentsWithFile();
206 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
207 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
208 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
210 Log_OC
.d(TAG
, "onCreate() end");
214 protected void onStart() {
216 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
217 refeshListOfFilesFragment();
221 protected void onDestroy() {
223 if (mDownloadConnection
!= null
)
224 unbindService(mDownloadConnection
);
225 if (mUploadConnection
!= null
)
226 unbindService(mUploadConnection
);
230 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
233 protected void onAccountSet(boolean stateWasRecovered
) {
234 super.onAccountSet(stateWasRecovered
);
235 if (getAccount() != null
) {
236 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
237 OCFile file
= getFile();
238 // get parent from path
239 String parentPath
= "";
241 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
242 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
243 // get parent from path
244 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
245 if (getStorageManager().getFileByPath(parentPath
) == null
)
246 file
= null
; // not able to know the directory where the file is uploading
248 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
252 // fall back to root folder
253 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
256 setNavigationListWithFolder(file
);
258 if (!stateWasRecovered
) {
259 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
260 initFragmentsWithFile();
261 if (file
.isFolder()) {
262 startSyncFolderOperation(file
);
266 updateFragmentsVisibility(!file
.isFolder());
267 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
273 private void setNavigationListWithFolder(OCFile file
) {
274 mDirectories
.clear();
275 OCFile fileIt
= file
;
277 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
278 if (fileIt
.isFolder()) {
279 mDirectories
.add(fileIt
.getFileName());
281 // get parent from path
282 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
283 fileIt
= getStorageManager().getFileByPath(parentPath
);
285 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
289 private void createMinFragments() {
290 OCFileListFragment listOfFiles
= new OCFileListFragment();
291 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
292 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
293 transaction
.commit();
296 private void initFragmentsWithFile() {
297 if (getAccount() != null
&& getFile() != null
) {
299 OCFileListFragment listOfFiles
= getListOfFilesFragment();
300 if (listOfFiles
!= null
) {
301 listOfFiles
.listDirectory(getCurrentDir());
303 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
307 OCFile file
= getFile();
308 Fragment secondFragment
= chooseInitialSecondFragment(file
);
309 if (secondFragment
!= null
) {
310 setSecondFragment(secondFragment
);
311 updateFragmentsVisibility(true
);
312 updateNavigationElementsInActionBar(file
);
315 cleanSecondFragment();
319 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
320 if (getAccount() == null
) {
321 Log
.wtf(TAG
, "\t account is NULL");
323 if (getFile() == null
) {
324 Log
.wtf(TAG
, "\t file is NULL");
329 private Fragment
chooseInitialSecondFragment(OCFile file
) {
330 Fragment secondFragment
= null
;
331 if (file
!= null
&& !file
.isFolder()) {
332 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
333 && file
.getLastSyncDateForProperties() > 0 // temporal fix
335 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
336 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
337 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
340 secondFragment
= new FileDetailFragment(file
, getAccount());
343 return secondFragment
;
348 * Replaces the second fragment managed by the activity with the received as
351 * Assumes never will be more than two fragments managed at the same time.
353 * @param fragment New second Fragment to set.
355 private void setSecondFragment(Fragment fragment
) {
356 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
357 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
358 transaction
.commit();
362 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
364 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
371 } else if (existsSecondFragment
) {
372 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
373 mLeftFragmentContainer
.setVisibility(View
.GONE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
380 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
381 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
383 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
384 mRightFragmentContainer
.setVisibility(View
.GONE
);
390 private OCFileListFragment
getListOfFilesFragment() {
391 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
392 if (listOfFiles
!= null
) {
393 return (OCFileListFragment
)listOfFiles
;
395 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
399 protected FileFragment
getSecondFragment() {
400 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
401 if (second
!= null
) {
402 return (FileFragment
)second
;
407 public void cleanSecondFragment() {
408 Fragment second
= getSecondFragment();
409 if (second
!= null
) {
410 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
414 updateFragmentsVisibility(false
);
415 updateNavigationElementsInActionBar(null
);
418 protected void refeshListOfFilesFragment() {
419 OCFileListFragment fileListFragment
= getListOfFilesFragment();
420 if (fileListFragment
!= null
) {
421 fileListFragment
.listDirectory();
425 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
426 FileFragment secondFragment
= getSecondFragment();
427 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
428 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
429 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
430 OCFile fileInFragment
= detailsFragment
.getFile();
431 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
432 // the user browsed to other file ; forget the automatic preview
433 mWaitingToPreview
= null
;
435 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
436 // grant that the right panel updates the progress bar
437 detailsFragment
.listenForTransferProgress();
438 detailsFragment
.updateFileDetails(true
, false
);
440 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
441 // update the right panel
442 boolean detailsFragmentChanged
= false
;
445 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
446 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
447 startMediaPreview(mWaitingToPreview
, 0, true
);
448 detailsFragmentChanged
= true
;
450 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
453 mWaitingToPreview
= null
;
455 if (!detailsFragmentChanged
) {
456 detailsFragment
.updateFileDetails(false
, (success
));
463 public boolean onCreateOptionsMenu(Menu menu
) {
464 MenuInflater inflater
= getSherlock().getMenuInflater();
465 inflater
.inflate(R
.menu
.main_menu
, menu
);
470 public boolean onOptionsItemSelected(MenuItem item
) {
471 boolean retval
= true
;
472 switch (item
.getItemId()) {
473 case R
.id
.action_create_dir
: {
474 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
475 dialog
.show(getSupportFragmentManager(), "createdirdialog");
478 case R
.id
.action_sync_account
: {
479 startSynchronization();
482 case R
.id
.action_upload
: {
483 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
486 case R
.id
.action_settings
: {
487 Intent settingsIntent
= new Intent(this, Preferences
.class);
488 startActivity(settingsIntent
);
491 case android
.R
.id
.home
: {
492 FileFragment second
= getSecondFragment();
493 OCFile currentDir
= getCurrentDir();
494 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
495 (second
!= null
&& second
.getFile() != null
)) {
502 retval
= super.onOptionsItemSelected(item
);
507 private void startSynchronization() {
508 Log_OC
.e(TAG
, "Got to start sync");
509 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
510 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
511 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
512 Bundle bundle
= new Bundle();
513 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
514 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
515 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
516 ContentResolver
.requestSync(
518 MainApp
.getAuthority(), bundle
);
520 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
521 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
522 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
523 builder
.setExpedited(true
);
524 builder
.setManual(true
);
526 SyncRequest request
= builder
.build();
527 ContentResolver
.requestSync(request
);
533 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
534 if (itemPosition
!= 0) {
535 String targetPath
= "";
536 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
537 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
539 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
540 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
541 if (targetFolder
!= null
) {
542 browseTo(targetFolder
);
545 // the next operation triggers a new call to this method, but it's necessary to
546 // ensure that the name exposed in the action bar is the current directory when the
547 // user selected it in the navigation list
548 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
549 getSupportActionBar().setSelectedNavigationItem(0);
555 * Called, when the user selected something for uploading
557 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
558 super.onActivityResult(requestCode
, resultCode
, data
);
560 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
561 requestSimpleUpload(data
, resultCode
);
563 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
564 requestMultipleUpload(data
, resultCode
);
569 private void requestMultipleUpload(Intent data
, int resultCode
) {
570 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
571 if (filePaths
!= null
) {
572 String
[] remotePaths
= new String
[filePaths
.length
];
573 String remotePathBase
= "";
574 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
575 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
577 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
578 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
579 for (int j
= 0; j
< remotePaths
.length
; j
++) {
580 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
583 Intent i
= new Intent(this, FileUploader
.class);
584 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
585 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
586 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
587 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
588 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
589 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
593 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
594 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
601 private void requestSimpleUpload(Intent data
, int resultCode
) {
602 String filepath
= null
;
604 Uri selectedImageUri
= data
.getData();
606 String filemanagerstring
= selectedImageUri
.getPath();
607 String selectedImagePath
= getPath(selectedImageUri
);
609 if (selectedImagePath
!= null
)
610 filepath
= selectedImagePath
;
612 filepath
= filemanagerstring
;
614 } catch (Exception e
) {
615 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
619 if (filepath
== null
) {
620 Log_OC
.e(TAG
, "Couldnt resolve path to file");
621 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
627 Intent i
= new Intent(this, FileUploader
.class);
628 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
630 String remotepath
= new String();
631 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
632 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
634 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
635 remotepath
+= OCFile
.PATH_SEPARATOR
;
636 remotepath
+= new File(filepath
).getName();
638 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
639 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
640 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
641 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
642 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
647 public void onBackPressed() {
648 OCFileListFragment listOfFiles
= getListOfFilesFragment();
649 if (mDualPane
|| getSecondFragment() == null
) {
650 if (listOfFiles
!= null
) { // should never be null, indeed
651 if (mDirectories
.getCount() <= 1) {
655 int levelsUp
= listOfFiles
.onBrowseUp();
656 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
661 if (listOfFiles
!= null
) { // should never be null, indeed
662 setFile(listOfFiles
.getCurrentFile());
664 cleanSecondFragment();
669 protected void onSaveInstanceState(Bundle outState
) {
670 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
671 Log_OC
.e(TAG
, "onSaveInstanceState() start");
672 super.onSaveInstanceState(outState
);
673 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
674 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
675 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
676 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
678 Log_OC
.d(TAG
, "onSaveInstanceState() end");
684 protected void onResume() {
686 Log_OC
.e(TAG
, "onResume() start");
688 // Listen for sync messages
689 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
690 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
691 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
692 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
693 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
694 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
695 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
696 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
697 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
699 // Listen for upload messages
700 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
701 mUploadFinishReceiver
= new UploadFinishReceiver();
702 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
704 // Listen for download messages
705 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
706 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
707 mDownloadFinishReceiver
= new DownloadFinishReceiver();
708 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
710 // Listen for messages from the OperationsService
712 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
713 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
714 mOperationsServiceReceiver = new OperationsServiceReceiver();
715 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
718 Log_OC
.d(TAG
, "onResume() end");
723 protected void onPause() {
725 Log_OC
.e(TAG
, "onPause() start");
726 if (mSyncBroadcastReceiver
!= null
) {
727 unregisterReceiver(mSyncBroadcastReceiver
);
728 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
729 mSyncBroadcastReceiver
= null
;
731 if (mUploadFinishReceiver
!= null
) {
732 unregisterReceiver(mUploadFinishReceiver
);
733 mUploadFinishReceiver
= null
;
735 if (mDownloadFinishReceiver
!= null
) {
736 unregisterReceiver(mDownloadFinishReceiver
);
737 mDownloadFinishReceiver
= null
;
740 if (mOperationsServiceReceiver != null) {
741 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
742 mOperationsServiceReceiver = null;
745 Log_OC
.d(TAG
, "onPause() end");
750 protected Dialog
onCreateDialog(int id
) {
751 Dialog dialog
= null
;
752 AlertDialog
.Builder builder
;
754 case DIALOG_SHORT_WAIT
: {
755 ProgressDialog working_dialog
= new ProgressDialog(this);
756 working_dialog
.setMessage(getResources().getString(
757 R
.string
.wait_a_moment
));
758 working_dialog
.setIndeterminate(true
);
759 working_dialog
.setCancelable(false
);
760 dialog
= working_dialog
;
763 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
765 String
[] items
= null
;
767 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
768 getString(R
.string
.actionbar_upload_from_apps
),
769 getString(R
.string
.actionbar_failed_instant_upload
) };
771 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
772 getString(R
.string
.actionbar_upload_from_apps
) };
774 if (InstantUploadActivity
.IS_ENABLED
)
779 builder
= new AlertDialog
.Builder(this);
780 builder
.setTitle(R
.string
.actionbar_upload
);
781 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
782 public void onClick(DialogInterface dialog
, int item
) {
785 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
786 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
787 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
789 // TODO create and handle new fragment
790 // LocalFileListFragment
792 } else if (item
== 1) {
793 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
794 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
795 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
796 ACTION_SELECT_CONTENT_FROM_APPS
);
797 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
798 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
799 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
800 startActivity(action
);
804 dialog
= builder
.create();
807 case DIALOG_CERT_NOT_SAVED
: {
808 builder
= new AlertDialog
.Builder(this);
809 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
810 builder
.setCancelable(false
);
811 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
813 public void onClick(DialogInterface dialog
, int which
) {
817 dialog
= builder
.create();
829 * Translates a content URI of an image to a physical path
831 * @param uri The URI to resolve
832 * @return The path to the image or null if it could not be found
834 public String
getPath(Uri uri
) {
835 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
836 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
837 if (cursor
!= null
) {
838 int column_index
= cursor
839 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
840 cursor
.moveToFirst();
841 return cursor
.getString(column_index
);
847 * Pushes a directory to the drop down list
848 * @param directory to push
849 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
851 public void pushDirname(OCFile directory
) {
852 if(!directory
.isFolder()){
853 throw new IllegalArgumentException("Only directories may be pushed!");
855 mDirectories
.insert(directory
.getFileName(), 0);
860 * Pops a directory name from the drop down list
861 * @return True, unless the stack is empty
863 public boolean popDirname() {
864 mDirectories
.remove(mDirectories
.getItem(0));
865 return !mDirectories
.isEmpty();
868 // Custom array adapter to override text colors
869 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
871 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
875 public View
getView(int position
, View convertView
, ViewGroup parent
) {
876 View v
= super.getView(position
, convertView
, parent
);
878 ((TextView
) v
).setTextColor(getResources().getColorStateList(
879 android
.R
.color
.white
));
881 fixRoot((TextView
) v
);
885 public View
getDropDownView(int position
, View convertView
,
887 View v
= super.getDropDownView(position
, convertView
, parent
);
889 ((TextView
) v
).setTextColor(getResources().getColorStateList(
890 android
.R
.color
.white
));
892 fixRoot((TextView
) v
);
896 private void fixRoot(TextView v
) {
897 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
898 v
.setText(R
.string
.default_display_name_for_root_folder
);
904 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
907 * {@link BroadcastReceiver} to enable syncing feedback in UI
910 public void onReceive(Context context
, Intent intent
) {
911 String event
= intent
.getAction();
912 Log_OC
.d(TAG
, "Received broadcast " + event
);
913 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
914 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
915 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
916 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
920 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
921 mSyncInProgress
= true
;
924 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
925 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
927 if (currentDir
== null
) {
928 // current folder was removed from the server
929 Toast
.makeText( FileDisplayActivity
.this,
930 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
936 if (currentFile
== null
&& !getFile().isFolder()) {
937 // currently selected file was removed in the server, and now we know it
938 cleanSecondFragment();
939 currentFile
= currentDir
;
942 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
943 OCFileListFragment fileListFragment
= getListOfFilesFragment();
944 if (fileListFragment
!= null
) {
945 fileListFragment
.listDirectory(currentDir
);
948 setFile(currentFile
);
951 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
954 if (synchResult != null &&
955 synchResult.isSuccess() &&
956 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
957 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
959 !mRefreshSharesInProgress &&
960 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
967 removeStickyBroadcast(intent
);
968 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
969 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
972 if (synchResult
!= null
) {
973 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
974 mLastSslUntrustedServerResult
= synchResult
;
981 private class UploadFinishReceiver
extends BroadcastReceiver
{
983 * Once the file upload has finished -> update view
984 * @author David A. Velasco
985 * {@link BroadcastReceiver} to enable upload feedback in UI
988 public void onReceive(Context context
, Intent intent
) {
989 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
990 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
991 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
992 OCFile currentDir
= getCurrentDir();
993 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
994 if (sameAccount
&& isDescendant
) {
995 refeshListOfFilesFragment();
1003 * Class waiting for broadcast events from the {@link FielDownloader} service.
1005 * Updates the UI when a download is started or finished, provided that it is relevant for the
1008 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1010 public void onReceive(Context context
, Intent intent
) {
1011 boolean sameAccount
= isSameAccount(context
, intent
);
1012 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1013 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1015 if (sameAccount
&& isDescendant
) {
1016 refeshListOfFilesFragment();
1017 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1020 if (mWaitingToSend
!= null
) {
1021 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1022 if (mWaitingToSend
.isDown()) {
1023 sendDownloadedFile();
1027 removeStickyBroadcast(intent
);
1030 private boolean isDescendant(String downloadedRemotePath
) {
1031 OCFile currentDir
= getCurrentDir();
1032 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1035 private boolean isSameAccount(Context context
, Intent intent
) {
1036 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1037 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1043 * Class waiting for broadcast events from the {@link OperationsService}.
1045 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1046 * operation performed in {@link OperationsService}.
1048 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1049 * probably all the operations associated to the app model.
1051 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1054 public void onReceive(Context context
, Intent intent
) {
1055 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1057 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1058 //mRefreshSharesInProgress = false;
1060 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1061 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1062 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1063 && getStorageManager() != null
1065 refeshListOfFilesFragment();
1067 if ((getSharesResult
!= null
) &&
1068 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1069 mLastSslUntrustedServerResult
= getSharesResult
;
1070 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1073 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1080 public void browseToRoot() {
1081 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1082 if (listOfFiles
!= null
) { // should never be null, indeed
1083 while (mDirectories
.getCount() > 1) {
1086 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1087 listOfFiles
.listDirectory(root
);
1088 setFile(listOfFiles
.getCurrentFile());
1089 startSyncFolderOperation(root
);
1091 cleanSecondFragment();
1095 public void browseTo(OCFile folder
) {
1096 if (folder
== null
|| !folder
.isFolder()) {
1097 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1099 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1100 if (listOfFiles
!= null
) {
1101 setNavigationListWithFolder(folder
);
1102 listOfFiles
.listDirectory(folder
);
1103 setFile(listOfFiles
.getCurrentFile());
1104 startSyncFolderOperation(folder
);
1106 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1108 cleanSecondFragment();
1115 * Updates action bar and second fragment, if in dual pane mode.
1118 public void onBrowsedDownTo(OCFile directory
) {
1119 pushDirname(directory
);
1120 cleanSecondFragment();
1123 startSyncFolderOperation(directory
);
1128 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1130 * @param file Image {@link OCFile} to show.
1133 public void startImagePreview(OCFile file
) {
1134 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1135 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1136 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1137 startActivity(showDetailsIntent
);
1141 * Stars the preview of an already down media {@link OCFile}.
1143 * @param file Media {@link OCFile} to preview.
1144 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1145 * @param autoplay When 'true', the playback will start without user interactions.
1148 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1149 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1150 setSecondFragment(mediaFragment
);
1151 updateFragmentsVisibility(true
);
1152 updateNavigationElementsInActionBar(file
);
1157 * Requests the download of the received {@link OCFile} , updates the UI
1158 * to monitor the download progress and prepares the activity to preview
1159 * or open the file when the download finishes.
1161 * @param file {@link OCFile} to download and preview.
1164 public void startDownloadForPreview(OCFile file
) {
1165 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1166 setSecondFragment(detailFragment
);
1167 mWaitingToPreview
= file
;
1168 requestForDownload();
1169 updateFragmentsVisibility(true
);
1170 updateNavigationElementsInActionBar(file
);
1176 * Shows the information of the {@link OCFile} received as a
1177 * parameter in the second fragment.
1179 * @param file {@link OCFile} whose details will be shown
1182 public void showDetails(OCFile file
) {
1183 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1184 setSecondFragment(detailFragment
);
1185 updateFragmentsVisibility(true
);
1186 updateNavigationElementsInActionBar(file
);
1194 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1195 ActionBar actionBar
= getSupportActionBar();
1196 if (chosenFile
== null
|| mDualPane
) {
1197 // only list of files - set for browsing through folders
1198 OCFile currentDir
= getCurrentDir();
1199 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1200 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1201 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1203 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1205 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1206 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1209 actionBar
.setDisplayHomeAsUpEnabled(true
);
1210 actionBar
.setDisplayShowTitleEnabled(true
);
1211 actionBar
.setTitle(chosenFile
.getFileName());
1212 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1221 public void onFileStateChanged() {
1222 refeshListOfFilesFragment();
1223 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1231 public FileDownloaderBinder
getFileDownloaderBinder() {
1232 return mDownloaderBinder
;
1240 public FileUploaderBinder
getFileUploaderBinder() {
1241 return mUploaderBinder
;
1245 /** Defines callbacks for service binding, passed to bindService() */
1246 private class ListServiceConnection
implements ServiceConnection
{
1249 public void onServiceConnected(ComponentName component
, IBinder service
) {
1250 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1251 Log_OC
.d(TAG
, "Download service connected");
1252 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1253 if (mWaitingToPreview
!= null
) {
1254 requestForDownload();
1257 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1258 Log_OC
.d(TAG
, "Upload service connected");
1259 mUploaderBinder
= (FileUploaderBinder
) service
;
1263 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1264 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1265 if (listOfFiles
!= null
) {
1266 listOfFiles
.listDirectory();
1268 FileFragment secondFragment
= getSecondFragment();
1269 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1270 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1271 detailFragment
.listenForTransferProgress();
1272 detailFragment
.updateFileDetails(false
, false
);
1277 public void onServiceDisconnected(ComponentName component
) {
1278 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1279 Log_OC
.d(TAG
, "Download service disconnected");
1280 mDownloaderBinder
= null
;
1281 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1282 Log_OC
.d(TAG
, "Upload service disconnected");
1283 mUploaderBinder
= null
;
1291 * Launch an intent to request the PIN code to the user before letting him use the app
1293 private void requestPinCode() {
1294 boolean pinStart
= false
;
1295 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1296 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1298 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1299 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1306 public void onSavedCertificate() {
1307 startSyncFolderOperation(getCurrentDir());
1312 public void onFailedSavingCertificate() {
1313 showDialog(DIALOG_CERT_NOT_SAVED
);
1317 public void onCancelCertificate() {
1322 * Updates the view associated to the activity after the finish of some operation over files
1323 * in the current account.
1325 * @param operation Removal operation performed.
1326 * @param result Result of the removal.
1329 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1330 super.onRemoteOperationFinish(operation
, result
);
1332 if (operation
instanceof RemoveFileOperation
) {
1333 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1335 } else if (operation
instanceof RenameFileOperation
) {
1336 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1338 } else if (operation
instanceof SynchronizeFileOperation
) {
1339 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1341 } else if (operation
instanceof CreateFolderOperation
) {
1342 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1344 } else if (operation
instanceof CreateShareOperation
) {
1345 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1347 } else if (operation
instanceof UnshareLinkOperation
) {
1348 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1355 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1356 if (result
.isSuccess()) {
1357 refreshShowDetails();
1358 refeshListOfFilesFragment();
1363 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1364 if (result
.isSuccess()) {
1365 refreshShowDetails();
1366 refeshListOfFilesFragment();
1367 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1368 cleanSecondFragment();
1369 refeshListOfFilesFragment();
1373 private void refreshShowDetails() {
1374 FileFragment details
= getSecondFragment();
1375 if (details
!= null
) {
1376 OCFile file
= details
.getFile();
1378 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1379 if (details
instanceof PreviewMediaFragment
) {
1380 // Refresh OCFile of the fragment
1381 ((PreviewMediaFragment
) details
).updateFile(file
);
1386 invalidateOptionsMenu();
1391 * Updates the view associated to the activity after the finish of an operation trying to remove a
1394 * @param operation Removal operation performed.
1395 * @param result Result of the removal.
1397 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1398 dismissLoadingDialog();
1399 if (result
.isSuccess()) {
1400 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1402 OCFile removedFile
= operation
.getFile();
1403 getSecondFragment();
1404 FileFragment second
= getSecondFragment();
1405 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1406 cleanSecondFragment();
1408 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1409 refeshListOfFilesFragment();
1413 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1415 if (result
.isSslRecoverableException()) {
1416 mLastSslUntrustedServerResult
= result
;
1417 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1423 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1425 * @param operation Creation operation performed.
1426 * @param result Result of the creation.
1428 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1429 if (result
.isSuccess()) {
1430 dismissLoadingDialog();
1431 refeshListOfFilesFragment();
1434 dismissLoadingDialog();
1435 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1436 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1439 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1442 } catch (NotFoundException e
) {
1443 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1451 * Updates the view associated to the activity after the finish of an operation trying to rename a
1454 * @param operation Renaming operation performed.
1455 * @param result Result of the renaming.
1457 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1458 dismissLoadingDialog();
1459 OCFile renamedFile
= operation
.getFile();
1460 if (result
.isSuccess()) {
1462 FileFragment details
= getSecondFragment();
1463 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1464 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1467 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1468 refeshListOfFilesFragment();
1472 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1473 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1475 // TODO throw again the new rename dialog
1476 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1477 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1480 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1482 if (result
.isSslRecoverableException()) {
1483 mLastSslUntrustedServerResult
= result
;
1484 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1491 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1492 dismissLoadingDialog();
1493 OCFile syncedFile
= operation
.getLocalFile();
1494 if (!result
.isSuccess()) {
1495 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1496 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1497 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1498 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1504 if (operation
.transferWasRequested()) {
1505 refeshListOfFilesFragment();
1506 onTransferStateChanged(syncedFile
, true
, true
);
1509 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1520 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1522 FileFragment details
= getSecondFragment();
1523 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1524 if (downloading
|| uploading
) {
1525 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1527 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1534 public void onDismiss(EditNameDialog dialog
) {
1535 if (dialog
.getResult()) {
1536 String newDirectoryName
= dialog
.getNewFilename().trim();
1537 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1538 if (newDirectoryName
.length() > 0) {
1539 String path
= getCurrentDir().getRemotePath();
1542 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1543 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1544 operation
.execute( getAccount(),
1545 FileDisplayActivity
.this,
1546 FileDisplayActivity
.this,
1548 FileDisplayActivity
.this);
1550 showLoadingDialog();
1556 private void requestForDownload() {
1557 Account account
= getAccount();
1558 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1559 Intent i
= new Intent(this, FileDownloader
.class);
1560 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1561 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1567 private OCFile
getCurrentDir() {
1568 OCFile file
= getFile();
1570 if (file
.isFolder()) {
1572 } else if (getStorageManager() != null
) {
1573 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1574 return getStorageManager().getFileByPath(parentPath
);
1580 public void startSyncFolderOperation(OCFile folder
) {
1581 long currentSyncTime
= System
.currentTimeMillis();
1583 mSyncInProgress
= true
;
1585 // perform folder synchronization
1586 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1589 getFileOperationsHelper().isSharedSupported(this),
1590 getStorageManager(),
1592 getApplicationContext()
1594 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1596 setSupportProgressBarIndeterminateVisibility(true
);
1600 private void startGetShares() {
1601 // Get shared files/folders
1602 Intent intent = new Intent(this, OperationsService.class);
1603 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1604 startService(intent);
1606 mRefreshSharesInProgress = true;
1611 * Show untrusted cert dialog
1613 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1614 // Show a dialog with the certificate info
1615 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1616 FragmentManager fm
= getSupportFragmentManager();
1617 FragmentTransaction ft
= fm
.beginTransaction();
1618 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1622 * Requests the download of the received {@link OCFile} , updates the UI
1623 * to monitor the download progress and prepares the activity to send the file
1624 * when the download finishes.
1626 * @param file {@link OCFile} to download and preview.
1629 public void startDownloadForSending(OCFile file
) {
1630 mWaitingToSend
= file
;
1631 requestForDownload(mWaitingToSend
);
1632 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1633 updateFragmentsVisibility(hasSecondFragment
);
1636 private void requestForDownload(OCFile file
) {
1637 Account account
= getAccount();
1638 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1639 Intent i
= new Intent(this, FileDownloader
.class);
1640 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1641 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1646 private void sendDownloadedFile(){
1647 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1648 mWaitingToSend
= null
;