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
.operations
.RemoteOperation
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
73 import com
.owncloud
.android
.operations
.CreateShareOperation
;
74 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
75 import com
.owncloud
.android
.operations
.RenameFileOperation
;
76 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
77 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
78 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
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
.SslUntrustedCertDialog
;
83 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
84 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
85 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
86 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
87 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
88 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
89 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
91 import com
.owncloud
.android
.utils
.DisplayUtils
;
92 import com
.owncloud
.android
.utils
.Log_OC
;
96 * Displays, what files the user has available in his ownCloud.
98 * @author Bartek Przybylski
99 * @author David A. Velasco
102 public class FileDisplayActivity
extends HookActivity
implements
103 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
, EditNameDialogListener
{
105 private ArrayAdapter
<String
> mDirectories
;
107 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
108 private UploadFinishReceiver mUploadFinishReceiver
;
109 private DownloadFinishReceiver mDownloadFinishReceiver
;
110 //private OperationsServiceReceiver mOperationsServiceReceiver;
111 private FileDownloaderBinder mDownloaderBinder
= null
;
112 private FileUploaderBinder mUploaderBinder
= null
;
113 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
114 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
116 private boolean mDualPane
;
117 private View mLeftFragmentContainer
;
118 private View mRightFragmentContainer
;
120 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
121 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
122 //private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
123 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
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
= 2;
130 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
132 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
133 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
135 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
137 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
138 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
140 private OCFile mWaitingToPreview
;
142 private boolean mSyncInProgress
= false
;
143 //private boolean mRefreshSharesInProgress = false;
145 private String DIALOG_UNTRUSTED_CERT
;
147 private OCFile mWaitingToSend
;
150 protected void onCreate(Bundle savedInstanceState
) {
151 Log_OC
.d(TAG
, "onCreate() start");
152 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
154 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
156 /// bindings to transference services
157 mUploadConnection
= new ListServiceConnection();
158 mDownloadConnection
= new ListServiceConnection();
159 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
160 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
162 // PIN CODE request ; best location is to decide, let's try this first
163 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
165 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
170 Intent observer_intent
= new Intent(this, FileObserverService
.class);
171 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
172 startService(observer_intent
);
174 /// Load of saved instance state
175 if(savedInstanceState
!= null
) {
176 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
177 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
178 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
179 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
182 mWaitingToPreview
= null
;
183 mSyncInProgress
= false
;
184 //mRefreshSharesInProgress = false;
185 mWaitingToSend
= null
;
190 // Inflate and set the layout view
191 setContentView(R
.layout
.files
);
192 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
193 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
194 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
195 if (savedInstanceState
== null
) {
196 createMinFragments();
198 Log_OC
.d(TAG
, "Init the secondFragment again");
200 initFragmentsWithFile();
205 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
206 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
207 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
209 Log_OC
.d(TAG
, "onCreate() end");
213 protected void onStart() {
215 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
216 refeshListOfFilesFragment();
220 protected void onDestroy() {
222 if (mDownloadConnection
!= null
)
223 unbindService(mDownloadConnection
);
224 if (mUploadConnection
!= null
)
225 unbindService(mUploadConnection
);
229 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
232 protected void onAccountSet(boolean stateWasRecovered
) {
233 super.onAccountSet(stateWasRecovered
);
234 if (getAccount() != null
) {
235 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
236 OCFile file
= getFile();
237 // get parent from path
238 String parentPath
= "";
240 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
241 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
242 // get parent from path
243 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
244 if (getStorageManager().getFileByPath(parentPath
) == null
)
245 file
= null
; // not able to know the directory where the file is uploading
247 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
251 // fall back to root folder
252 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
255 setNavigationListWithFolder(file
);
257 if (!stateWasRecovered
) {
258 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
259 initFragmentsWithFile();
260 if (file
.isFolder()) {
261 startSyncFolderOperation(file
);
265 updateFragmentsVisibility(!file
.isFolder());
266 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
272 private void setNavigationListWithFolder(OCFile file
) {
273 mDirectories
.clear();
274 OCFile fileIt
= file
;
276 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
277 if (fileIt
.isFolder()) {
278 mDirectories
.add(fileIt
.getFileName());
280 // get parent from path
281 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
282 fileIt
= getStorageManager().getFileByPath(parentPath
);
284 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
288 private void createMinFragments() {
289 OCFileListFragment listOfFiles
= new OCFileListFragment();
290 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
291 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
292 transaction
.commit();
295 private void initFragmentsWithFile() {
296 if (getAccount() != null
&& getFile() != null
) {
298 OCFileListFragment listOfFiles
= getListOfFilesFragment();
299 if (listOfFiles
!= null
) {
300 listOfFiles
.listDirectory(getCurrentDir());
302 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
306 OCFile file
= getFile();
307 Fragment secondFragment
= chooseInitialSecondFragment(file
);
308 if (secondFragment
!= null
) {
309 setSecondFragment(secondFragment
);
310 updateFragmentsVisibility(true
);
311 updateNavigationElementsInActionBar(file
);
314 cleanSecondFragment();
318 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
319 if (getAccount() == null
) {
320 Log
.wtf(TAG
, "\t account is NULL");
322 if (getFile() == null
) {
323 Log
.wtf(TAG
, "\t file is NULL");
328 private Fragment
chooseInitialSecondFragment(OCFile file
) {
329 Fragment secondFragment
= null
;
330 if (file
!= null
&& !file
.isFolder()) {
331 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
332 && file
.getLastSyncDateForProperties() > 0 // temporal fix
334 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
335 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
336 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
339 secondFragment
= new FileDetailFragment(file
, getAccount());
342 return secondFragment
;
347 * Replaces the second fragment managed by the activity with the received as
350 * Assumes never will be more than two fragments managed at the same time.
352 * @param fragment New second Fragment to set.
354 private void setSecondFragment(Fragment fragment
) {
355 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
356 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
357 transaction
.commit();
361 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
363 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
366 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
370 } else if (existsSecondFragment
) {
371 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
372 mLeftFragmentContainer
.setVisibility(View
.GONE
);
374 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
379 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
380 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
382 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
383 mRightFragmentContainer
.setVisibility(View
.GONE
);
389 private OCFileListFragment
getListOfFilesFragment() {
390 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
391 if (listOfFiles
!= null
) {
392 return (OCFileListFragment
)listOfFiles
;
394 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
398 protected FileFragment
getSecondFragment() {
399 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
400 if (second
!= null
) {
401 return (FileFragment
)second
;
406 public void cleanSecondFragment() {
407 Fragment second
= getSecondFragment();
408 if (second
!= null
) {
409 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
413 updateFragmentsVisibility(false
);
414 updateNavigationElementsInActionBar(null
);
417 protected void refeshListOfFilesFragment() {
418 OCFileListFragment fileListFragment
= getListOfFilesFragment();
419 if (fileListFragment
!= null
) {
420 fileListFragment
.listDirectory();
424 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
425 FileFragment secondFragment
= getSecondFragment();
426 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
427 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
428 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
429 OCFile fileInFragment
= detailsFragment
.getFile();
430 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
431 // the user browsed to other file ; forget the automatic preview
432 mWaitingToPreview
= null
;
434 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
435 // grant that the right panel updates the progress bar
436 detailsFragment
.listenForTransferProgress();
437 detailsFragment
.updateFileDetails(true
, false
);
439 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
440 // update the right panel
441 boolean detailsFragmentChanged
= false
;
444 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
445 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
446 startMediaPreview(mWaitingToPreview
, 0, true
);
447 detailsFragmentChanged
= true
;
449 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
452 mWaitingToPreview
= null
;
454 if (!detailsFragmentChanged
) {
455 detailsFragment
.updateFileDetails(false
, (success
));
462 public boolean onCreateOptionsMenu(Menu menu
) {
463 MenuInflater inflater
= getSherlock().getMenuInflater();
464 inflater
.inflate(R
.menu
.main_menu
, menu
);
469 public boolean onOptionsItemSelected(MenuItem item
) {
470 boolean retval
= true
;
471 switch (item
.getItemId()) {
472 case R
.id
.action_create_dir
: {
473 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
474 dialog
.show(getSupportFragmentManager(), "createdirdialog");
477 case R
.id
.action_sync_account
: {
478 startSynchronization();
481 case R
.id
.action_upload
: {
482 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
485 case R
.id
.action_settings
: {
486 Intent settingsIntent
= new Intent(this, Preferences
.class);
487 startActivity(settingsIntent
);
490 case android
.R
.id
.home
: {
491 FileFragment second
= getSecondFragment();
492 OCFile currentDir
= getCurrentDir();
493 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
494 (second
!= null
&& second
.getFile() != null
)) {
501 retval
= super.onOptionsItemSelected(item
);
506 private void startSynchronization() {
507 Log_OC
.e(TAG
, "Got to start sync");
508 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
509 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
510 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
511 Bundle bundle
= new Bundle();
512 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
513 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
514 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
515 ContentResolver
.requestSync(
517 MainApp
.getAuthority(), bundle
);
519 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
520 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
521 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
522 builder
.setExpedited(true
);
523 builder
.setManual(true
);
525 SyncRequest request
= builder
.build();
526 ContentResolver
.requestSync(request
);
532 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
533 if (itemPosition
!= 0) {
534 String targetPath
= "";
535 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
536 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
538 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
539 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
540 if (targetFolder
!= null
) {
541 browseTo(targetFolder
);
544 // the next operation triggers a new call to this method, but it's necessary to
545 // ensure that the name exposed in the action bar is the current directory when the
546 // user selected it in the navigation list
547 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
548 getSupportActionBar().setSelectedNavigationItem(0);
554 * Called, when the user selected something for uploading
556 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
557 super.onActivityResult(requestCode
, resultCode
, data
);
559 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
560 requestSimpleUpload(data
, resultCode
);
562 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
563 requestMultipleUpload(data
, resultCode
);
568 private void requestMultipleUpload(Intent data
, int resultCode
) {
569 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
570 if (filePaths
!= null
) {
571 String
[] remotePaths
= new String
[filePaths
.length
];
572 String remotePathBase
= "";
573 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
574 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
576 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
577 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
578 for (int j
= 0; j
< remotePaths
.length
; j
++) {
579 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
582 Intent i
= new Intent(this, FileUploader
.class);
583 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
584 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
585 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
586 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
587 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
588 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
592 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
593 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
600 private void requestSimpleUpload(Intent data
, int resultCode
) {
601 String filepath
= null
;
603 Uri selectedImageUri
= data
.getData();
605 String filemanagerstring
= selectedImageUri
.getPath();
606 String selectedImagePath
= getPath(selectedImageUri
);
608 if (selectedImagePath
!= null
)
609 filepath
= selectedImagePath
;
611 filepath
= filemanagerstring
;
613 } catch (Exception e
) {
614 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
618 if (filepath
== null
) {
619 Log_OC
.e(TAG
, "Couldnt resolve path to file");
620 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
626 Intent i
= new Intent(this, FileUploader
.class);
627 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
629 String remotepath
= new String();
630 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
631 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
633 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
634 remotepath
+= OCFile
.PATH_SEPARATOR
;
635 remotepath
+= new File(filepath
).getName();
637 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
638 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
639 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
640 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
641 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
646 public void onBackPressed() {
647 OCFileListFragment listOfFiles
= getListOfFilesFragment();
648 if (mDualPane
|| getSecondFragment() == null
) {
649 if (listOfFiles
!= null
) { // should never be null, indeed
650 if (mDirectories
.getCount() <= 1) {
654 int levelsUp
= listOfFiles
.onBrowseUp();
655 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
660 if (listOfFiles
!= null
) { // should never be null, indeed
661 setFile(listOfFiles
.getCurrentFile());
663 cleanSecondFragment();
668 protected void onSaveInstanceState(Bundle outState
) {
669 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
670 Log_OC
.e(TAG
, "onSaveInstanceState() start");
671 super.onSaveInstanceState(outState
);
672 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
673 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
674 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
675 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
677 Log_OC
.d(TAG
, "onSaveInstanceState() end");
683 protected void onResume() {
685 Log_OC
.e(TAG
, "onResume() start");
687 // Listen for sync messages
688 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
689 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
690 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
691 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
692 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
693 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
694 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
695 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
696 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
698 // Listen for upload messages
699 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
700 mUploadFinishReceiver
= new UploadFinishReceiver();
701 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
703 // Listen for download messages
704 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
705 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
706 mDownloadFinishReceiver
= new DownloadFinishReceiver();
707 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
709 // Listen for messages from the OperationsService
711 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
712 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
713 mOperationsServiceReceiver = new OperationsServiceReceiver();
714 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
717 Log_OC
.d(TAG
, "onResume() end");
722 protected void onPause() {
724 Log_OC
.e(TAG
, "onPause() start");
725 if (mSyncBroadcastReceiver
!= null
) {
726 unregisterReceiver(mSyncBroadcastReceiver
);
727 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
728 mSyncBroadcastReceiver
= null
;
730 if (mUploadFinishReceiver
!= null
) {
731 unregisterReceiver(mUploadFinishReceiver
);
732 mUploadFinishReceiver
= null
;
734 if (mDownloadFinishReceiver
!= null
) {
735 unregisterReceiver(mDownloadFinishReceiver
);
736 mDownloadFinishReceiver
= null
;
739 if (mOperationsServiceReceiver != null) {
740 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
741 mOperationsServiceReceiver = null;
744 Log_OC
.d(TAG
, "onPause() end");
749 protected Dialog
onCreateDialog(int id
) {
750 Dialog dialog
= null
;
751 AlertDialog
.Builder builder
;
753 case DIALOG_SHORT_WAIT
: {
754 ProgressDialog working_dialog
= new ProgressDialog(this);
755 working_dialog
.setMessage(getResources().getString(
756 R
.string
.wait_a_moment
));
757 working_dialog
.setIndeterminate(true
);
758 working_dialog
.setCancelable(false
);
759 dialog
= working_dialog
;
762 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
764 String
[] items
= null
;
766 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
767 getString(R
.string
.actionbar_upload_from_apps
),
768 getString(R
.string
.actionbar_failed_instant_upload
) };
770 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
771 getString(R
.string
.actionbar_upload_from_apps
) };
773 if (InstantUploadActivity
.IS_ENABLED
)
778 builder
= new AlertDialog
.Builder(this);
779 builder
.setTitle(R
.string
.actionbar_upload
);
780 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
781 public void onClick(DialogInterface dialog
, int item
) {
784 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
785 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
786 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
788 // TODO create and handle new fragment
789 // LocalFileListFragment
791 } else if (item
== 1) {
792 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
793 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
794 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
795 ACTION_SELECT_CONTENT_FROM_APPS
);
796 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
797 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
798 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
799 startActivity(action
);
803 dialog
= builder
.create();
806 case DIALOG_CERT_NOT_SAVED
: {
807 builder
= new AlertDialog
.Builder(this);
808 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
809 builder
.setCancelable(false
);
810 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
812 public void onClick(DialogInterface dialog
, int which
) {
816 dialog
= builder
.create();
828 * Translates a content URI of an image to a physical path
830 * @param uri The URI to resolve
831 * @return The path to the image or null if it could not be found
833 public String
getPath(Uri uri
) {
834 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
835 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
836 if (cursor
!= null
) {
837 int column_index
= cursor
838 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
839 cursor
.moveToFirst();
840 return cursor
.getString(column_index
);
846 * Pushes a directory to the drop down list
847 * @param directory to push
848 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
850 public void pushDirname(OCFile directory
) {
851 if(!directory
.isFolder()){
852 throw new IllegalArgumentException("Only directories may be pushed!");
854 mDirectories
.insert(directory
.getFileName(), 0);
859 * Pops a directory name from the drop down list
860 * @return True, unless the stack is empty
862 public boolean popDirname() {
863 mDirectories
.remove(mDirectories
.getItem(0));
864 return !mDirectories
.isEmpty();
867 // Custom array adapter to override text colors
868 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
870 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
874 public View
getView(int position
, View convertView
, ViewGroup parent
) {
875 View v
= super.getView(position
, convertView
, parent
);
877 ((TextView
) v
).setTextColor(getResources().getColorStateList(
878 android
.R
.color
.white
));
880 fixRoot((TextView
) v
);
884 public View
getDropDownView(int position
, View convertView
,
886 View v
= super.getDropDownView(position
, convertView
, parent
);
888 ((TextView
) v
).setTextColor(getResources().getColorStateList(
889 android
.R
.color
.white
));
891 fixRoot((TextView
) v
);
895 private void fixRoot(TextView v
) {
896 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
897 v
.setText(R
.string
.default_display_name_for_root_folder
);
903 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
906 * {@link BroadcastReceiver} to enable syncing feedback in UI
909 public void onReceive(Context context
, Intent intent
) {
910 String event
= intent
.getAction();
911 Log_OC
.d(TAG
, "Received broadcast " + event
);
912 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
913 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
914 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
915 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
919 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
920 mSyncInProgress
= true
;
923 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
924 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
926 if (currentDir
== null
) {
927 // current folder was removed from the server
928 Toast
.makeText( FileDisplayActivity
.this,
929 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
935 if (currentFile
== null
&& !getFile().isFolder()) {
936 // currently selected file was removed in the server, and now we know it
937 cleanSecondFragment();
938 currentFile
= currentDir
;
941 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
942 OCFileListFragment fileListFragment
= getListOfFilesFragment();
943 if (fileListFragment
!= null
) {
944 fileListFragment
.listDirectory(currentDir
);
947 setFile(currentFile
);
950 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
953 if (synchResult != null &&
954 synchResult.isSuccess() &&
955 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
956 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
958 !mRefreshSharesInProgress &&
959 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
966 removeStickyBroadcast(intent
);
967 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
968 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
971 if (synchResult
!= null
) {
972 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
973 mLastSslUntrustedServerResult
= synchResult
;
980 private class UploadFinishReceiver
extends BroadcastReceiver
{
982 * Once the file upload has finished -> update view
983 * @author David A. Velasco
984 * {@link BroadcastReceiver} to enable upload feedback in UI
987 public void onReceive(Context context
, Intent intent
) {
988 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
989 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
990 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
991 OCFile currentDir
= getCurrentDir();
992 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
993 if (sameAccount
&& isDescendant
) {
994 refeshListOfFilesFragment();
1002 * Class waiting for broadcast events from the {@link FielDownloader} service.
1004 * Updates the UI when a download is started or finished, provided that it is relevant for the
1007 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1009 public void onReceive(Context context
, Intent intent
) {
1010 boolean sameAccount
= isSameAccount(context
, intent
);
1011 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1012 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1014 if (sameAccount
&& isDescendant
) {
1015 refeshListOfFilesFragment();
1016 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1019 if (mWaitingToSend
!= null
) {
1020 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1021 if (mWaitingToSend
.isDown()) {
1022 sendDownloadedFile();
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 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
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 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1199 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1200 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1202 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1204 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1205 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1208 actionBar
.setDisplayHomeAsUpEnabled(true
);
1209 actionBar
.setDisplayShowTitleEnabled(true
);
1210 actionBar
.setTitle(chosenFile
.getFileName());
1211 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1220 public void onFileStateChanged() {
1221 refeshListOfFilesFragment();
1222 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1230 public FileDownloaderBinder
getFileDownloaderBinder() {
1231 return mDownloaderBinder
;
1239 public FileUploaderBinder
getFileUploaderBinder() {
1240 return mUploaderBinder
;
1244 /** Defines callbacks for service binding, passed to bindService() */
1245 private class ListServiceConnection
implements ServiceConnection
{
1248 public void onServiceConnected(ComponentName component
, IBinder service
) {
1249 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1250 Log_OC
.d(TAG
, "Download service connected");
1251 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1252 if (mWaitingToPreview
!= null
) {
1253 requestForDownload();
1256 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1257 Log_OC
.d(TAG
, "Upload service connected");
1258 mUploaderBinder
= (FileUploaderBinder
) service
;
1262 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1263 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1264 if (listOfFiles
!= null
) {
1265 listOfFiles
.listDirectory();
1267 FileFragment secondFragment
= getSecondFragment();
1268 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1269 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1270 detailFragment
.listenForTransferProgress();
1271 detailFragment
.updateFileDetails(false
, false
);
1276 public void onServiceDisconnected(ComponentName component
) {
1277 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1278 Log_OC
.d(TAG
, "Download service disconnected");
1279 mDownloaderBinder
= null
;
1280 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1281 Log_OC
.d(TAG
, "Upload service disconnected");
1282 mUploaderBinder
= null
;
1290 * Launch an intent to request the PIN code to the user before letting him use the app
1292 private void requestPinCode() {
1293 boolean pinStart
= false
;
1294 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1295 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1297 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1298 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1305 public void onSavedCertificate() {
1306 startSyncFolderOperation(getCurrentDir());
1311 public void onFailedSavingCertificate() {
1312 showDialog(DIALOG_CERT_NOT_SAVED
);
1317 * Updates the view associated to the activity after the finish of some operation over files
1318 * in the current account.
1320 * @param operation Removal operation performed.
1321 * @param result Result of the removal.
1324 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1325 super.onRemoteOperationFinish(operation
, result
);
1327 if (operation
instanceof RemoveFileOperation
) {
1328 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1330 } else if (operation
instanceof RenameFileOperation
) {
1331 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1333 } else if (operation
instanceof SynchronizeFileOperation
) {
1334 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1336 } else if (operation
instanceof CreateFolderOperation
) {
1337 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1339 } else if (operation
instanceof CreateShareOperation
) {
1340 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1342 } else if (operation
instanceof UnshareLinkOperation
) {
1343 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1350 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1351 if (result
.isSuccess()) {
1352 refreshShowDetails();
1353 refeshListOfFilesFragment();
1358 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1359 if (result
.isSuccess()) {
1360 refreshShowDetails();
1361 refeshListOfFilesFragment();
1362 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1363 cleanSecondFragment();
1364 refeshListOfFilesFragment();
1368 private void refreshShowDetails() {
1369 FileFragment details
= getSecondFragment();
1370 if (details
!= null
) {
1371 OCFile file
= details
.getFile();
1373 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1374 if (details
instanceof PreviewMediaFragment
) {
1375 // Refresh OCFile of the fragment
1376 ((PreviewMediaFragment
) details
).updateFile(file
);
1381 invalidateOptionsMenu();
1386 * Updates the view associated to the activity after the finish of an operation trying to remove a
1389 * @param operation Removal operation performed.
1390 * @param result Result of the removal.
1392 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1393 dismissLoadingDialog();
1394 if (result
.isSuccess()) {
1395 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1397 OCFile removedFile
= operation
.getFile();
1398 getSecondFragment();
1399 FileFragment second
= getSecondFragment();
1400 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1401 cleanSecondFragment();
1403 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1404 refeshListOfFilesFragment();
1408 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1410 if (result
.isSslRecoverableException()) {
1411 mLastSslUntrustedServerResult
= result
;
1412 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1418 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1420 * @param operation Creation operation performed.
1421 * @param result Result of the creation.
1423 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1424 if (result
.isSuccess()) {
1425 dismissLoadingDialog();
1426 refeshListOfFilesFragment();
1429 dismissLoadingDialog();
1430 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1431 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1434 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1437 } catch (NotFoundException e
) {
1438 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1446 * Updates the view associated to the activity after the finish of an operation trying to rename a
1449 * @param operation Renaming operation performed.
1450 * @param result Result of the renaming.
1452 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1453 dismissLoadingDialog();
1454 OCFile renamedFile
= operation
.getFile();
1455 if (result
.isSuccess()) {
1457 FileFragment details
= getSecondFragment();
1458 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1459 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1462 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1463 refeshListOfFilesFragment();
1467 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1468 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1470 // TODO throw again the new rename dialog
1471 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1472 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1475 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1477 if (result
.isSslRecoverableException()) {
1478 mLastSslUntrustedServerResult
= result
;
1479 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1486 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1487 dismissLoadingDialog();
1488 OCFile syncedFile
= operation
.getLocalFile();
1489 if (!result
.isSuccess()) {
1490 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1491 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1492 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1493 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1499 if (operation
.transferWasRequested()) {
1500 refeshListOfFilesFragment();
1501 onTransferStateChanged(syncedFile
, true
, true
);
1504 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1515 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1517 FileFragment details
= getSecondFragment();
1518 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1519 if (downloading
|| uploading
) {
1520 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1522 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1529 public void onDismiss(EditNameDialog dialog
) {
1530 if (dialog
.getResult()) {
1531 String newDirectoryName
= dialog
.getNewFilename().trim();
1532 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1533 if (newDirectoryName
.length() > 0) {
1534 String path
= getCurrentDir().getRemotePath();
1537 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1538 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1539 operation
.execute( getAccount(),
1540 FileDisplayActivity
.this,
1541 FileDisplayActivity
.this,
1543 FileDisplayActivity
.this);
1545 showLoadingDialog();
1551 private void requestForDownload() {
1552 Account account
= getAccount();
1553 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1554 Intent i
= new Intent(this, FileDownloader
.class);
1555 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1556 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1562 private OCFile
getCurrentDir() {
1563 OCFile file
= getFile();
1565 if (file
.isFolder()) {
1567 } else if (getStorageManager() != null
) {
1568 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1569 return getStorageManager().getFileByPath(parentPath
);
1575 public void startSyncFolderOperation(OCFile folder
) {
1576 long currentSyncTime
= System
.currentTimeMillis();
1578 mSyncInProgress
= true
;
1580 // perform folder synchronization
1581 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1584 getFileOperationsHelper().isSharedSupported(this),
1585 getStorageManager(),
1587 getApplicationContext()
1589 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1591 setSupportProgressBarIndeterminateVisibility(true
);
1595 private void startGetShares() {
1596 // Get shared files/folders
1597 Intent intent = new Intent(this, OperationsService.class);
1598 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1599 startService(intent);
1601 mRefreshSharesInProgress = true;
1606 * Show untrusted cert dialog
1608 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1609 // Show a dialog with the certificate info
1610 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstance(result
, this);
1611 FragmentManager fm
= getSupportFragmentManager();
1612 FragmentTransaction ft
= fm
.beginTransaction();
1613 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1618 * Dismiss untrusted cert dialog
1620 public void dismissUntrustedCertDialog(){
1621 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_UNTRUSTED_CERT
);
1623 SslUntrustedCertDialog dialog
= (SslUntrustedCertDialog
) frag
;
1629 public void onCancelCertificate() {
1630 // TODO Auto-generated method stub
1635 * Requests the download of the received {@link OCFile} , updates the UI
1636 * to monitor the download progress and prepares the activity to send the file
1637 * when the download finishes.
1639 * @param file {@link OCFile} to download and preview.
1642 public void startDownloadForSending(OCFile file
) {
1643 mWaitingToSend
= file
;
1644 requestForDownload(mWaitingToSend
);
1645 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1646 updateFragmentsVisibility(hasSecondFragment
);
1649 private void requestForDownload(OCFile file
) {
1650 Account account
= getAccount();
1651 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1652 Intent i
= new Intent(this, FileDownloader
.class);
1653 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1654 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1659 private void sendDownloadedFile(){
1660 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1661 mWaitingToSend
= null
;