1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.Dialog
;
26 import android
.app
.ProgressDialog
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.ComponentName
;
29 import android
.content
.ContentResolver
;
30 import android
.content
.Context
;
31 import android
.content
.DialogInterface
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.content
.SyncRequest
;
37 import android
.content
.res
.Configuration
;
38 import android
.content
.res
.Resources
.NotFoundException
;
39 import android
.database
.Cursor
;
40 import android
.net
.Uri
;
41 import android
.os
.Bundle
;
42 import android
.os
.IBinder
;
43 import android
.preference
.PreferenceManager
;
44 import android
.provider
.MediaStore
;
45 import android
.support
.v4
.app
.Fragment
;
46 import android
.support
.v4
.app
.FragmentTransaction
;
47 //import android.support.v4.content.LocalBroadcastManager;
48 import android
.util
.Log
;
49 import android
.view
.View
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ArrayAdapter
;
52 import android
.widget
.TextView
;
53 import android
.widget
.Toast
;
55 import com
.actionbarsherlock
.app
.ActionBar
;
56 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
57 import com
.actionbarsherlock
.view
.Menu
;
58 import com
.actionbarsherlock
.view
.MenuInflater
;
59 import com
.actionbarsherlock
.view
.MenuItem
;
60 import com
.actionbarsherlock
.view
.Window
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileObserverService
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
71 import com
.owncloud
.android
.lib
.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
.EditNameDialog
.EditNameDialogListener
;
84 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
86 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
87 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
88 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
89 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
92 import com
.owncloud
.android
.utils
.DisplayUtils
;
93 import com
.owncloud
.android
.utils
.Log_OC
;
97 * Displays, what files the user has available in his ownCloud.
99 * @author Bartek Przybylski
100 * @author David A. Velasco
103 public class FileDisplayActivity
extends HookActivity
implements
104 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, EditNameDialogListener
{
106 private ArrayAdapter
<String
> mDirectories
;
108 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
109 private UploadFinishReceiver mUploadFinishReceiver
;
110 private DownloadFinishReceiver mDownloadFinishReceiver
;
111 //private OperationsServiceReceiver mOperationsServiceReceiver;
112 private FileDownloaderBinder mDownloaderBinder
= null
;
113 private FileUploaderBinder mUploaderBinder
= null
;
114 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
115 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
117 private boolean mDualPane
;
118 private View mLeftFragmentContainer
;
119 private View mRightFragmentContainer
;
121 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
122 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
123 //private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
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
= 3;
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 OCFile mWaitingToSend
;
149 protected void onCreate(Bundle savedInstanceState
) {
150 Log_OC
.d(TAG
, "onCreate() start");
151 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
153 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
155 /// bindings to transference services
156 mUploadConnection
= new ListServiceConnection();
157 mDownloadConnection
= new ListServiceConnection();
158 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
159 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
161 // PIN CODE request ; best location is to decide, let's try this first
162 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
164 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
169 Intent observer_intent
= new Intent(this, FileObserverService
.class);
170 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
171 startService(observer_intent
);
173 /// Load of saved instance state
174 if(savedInstanceState
!= null
) {
175 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
178 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
181 mWaitingToPreview
= null
;
182 mSyncInProgress
= false
;
183 //mRefreshSharesInProgress = false;
184 mWaitingToSend
= null
;
189 // Inflate and set the layout view
190 setContentView(R
.layout
.files
);
191 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
192 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
193 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
194 if (savedInstanceState
== null
) {
195 createMinFragments();
197 Log_OC
.d(TAG
, "Init the secondFragment again");
199 initFragmentsWithFile();
204 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
205 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
206 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
208 Log_OC
.d(TAG
, "onCreate() end");
212 protected void onStart() {
214 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 refeshListOfFilesFragment();
219 protected void onDestroy() {
221 if (mDownloadConnection
!= null
)
222 unbindService(mDownloadConnection
);
223 if (mUploadConnection
!= null
)
224 unbindService(mUploadConnection
);
228 public void onConfigurationChanged(Configuration newConfig
) {
229 super.onConfigurationChanged(newConfig
);
233 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
236 protected void onAccountSet(boolean stateWasRecovered
) {
237 super.onAccountSet(stateWasRecovered
);
238 if (getAccount() != null
) {
239 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
240 OCFile file
= getFile();
241 // get parent from path
242 String parentPath
= "";
244 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
245 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
246 // get parent from path
247 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
248 if (getStorageManager().getFileByPath(parentPath
) == null
)
249 file
= null
; // not able to know the directory where the file is uploading
251 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
255 // fall back to root folder
256 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
259 setNavigationListWithFolder(file
);
261 if (!stateWasRecovered
) {
262 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
263 initFragmentsWithFile();
264 if (file
.isFolder()) {
265 startSyncFolderOperation(file
);
269 updateFragmentsVisibility(!file
.isFolder());
270 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
276 private void setNavigationListWithFolder(OCFile file
) {
277 mDirectories
.clear();
278 OCFile fileIt
= file
;
280 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
281 if (fileIt
.isFolder()) {
282 mDirectories
.add(fileIt
.getFileName());
284 // get parent from path
285 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
286 fileIt
= getStorageManager().getFileByPath(parentPath
);
288 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
292 private void createMinFragments() {
293 OCFileListFragment listOfFiles
= new OCFileListFragment();
294 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
295 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
296 transaction
.commit();
299 private void initFragmentsWithFile() {
300 if (getAccount() != null
&& getFile() != null
) {
302 OCFileListFragment listOfFiles
= getListOfFilesFragment();
303 if (listOfFiles
!= null
) {
304 listOfFiles
.listDirectory(getCurrentDir());
306 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
310 OCFile file
= getFile();
311 Fragment secondFragment
= chooseInitialSecondFragment(file
);
312 if (secondFragment
!= null
) {
313 setSecondFragment(secondFragment
);
314 updateFragmentsVisibility(true
);
315 updateNavigationElementsInActionBar(file
);
318 cleanSecondFragment();
322 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
323 if (getAccount() == null
) {
324 Log
.wtf(TAG
, "\t account is NULL");
326 if (getFile() == null
) {
327 Log
.wtf(TAG
, "\t file is NULL");
332 private Fragment
chooseInitialSecondFragment(OCFile file
) {
333 Fragment secondFragment
= null
;
334 if (file
!= null
&& !file
.isFolder()) {
335 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
336 && file
.getLastSyncDateForProperties() > 0 // temporal fix
338 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
339 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
340 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
343 secondFragment
= new FileDetailFragment(file
, getAccount());
346 return secondFragment
;
351 * Replaces the second fragment managed by the activity with the received as
354 * Assumes never will be more than two fragments managed at the same time.
356 * @param fragment New second Fragment to set.
358 private void setSecondFragment(Fragment fragment
) {
359 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
360 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
361 transaction
.commit();
365 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
367 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
370 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
374 } else if (existsSecondFragment
) {
375 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
376 mLeftFragmentContainer
.setVisibility(View
.GONE
);
378 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
383 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
384 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
386 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
387 mRightFragmentContainer
.setVisibility(View
.GONE
);
393 private OCFileListFragment
getListOfFilesFragment() {
394 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
395 if (listOfFiles
!= null
) {
396 return (OCFileListFragment
)listOfFiles
;
398 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
402 protected FileFragment
getSecondFragment() {
403 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
404 if (second
!= null
) {
405 return (FileFragment
)second
;
410 public void cleanSecondFragment() {
411 Fragment second
= getSecondFragment();
412 if (second
!= null
) {
413 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
417 updateFragmentsVisibility(false
);
418 updateNavigationElementsInActionBar(null
);
421 protected void refeshListOfFilesFragment() {
422 OCFileListFragment fileListFragment
= getListOfFilesFragment();
423 if (fileListFragment
!= null
) {
424 fileListFragment
.listDirectory();
428 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
429 FileFragment secondFragment
= getSecondFragment();
430 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
431 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
432 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
433 OCFile fileInFragment
= detailsFragment
.getFile();
434 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
435 // the user browsed to other file ; forget the automatic preview
436 mWaitingToPreview
= null
;
438 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
439 // grant that the right panel updates the progress bar
440 detailsFragment
.listenForTransferProgress();
441 detailsFragment
.updateFileDetails(true
, false
);
443 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
444 // update the right panel
445 boolean detailsFragmentChanged
= false
;
448 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
449 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
450 startMediaPreview(mWaitingToPreview
, 0, true
);
451 detailsFragmentChanged
= true
;
453 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
456 mWaitingToPreview
= null
;
458 if (!detailsFragmentChanged
) {
459 detailsFragment
.updateFileDetails(false
, (success
));
466 public boolean onCreateOptionsMenu(Menu menu
) {
467 MenuInflater inflater
= getSherlock().getMenuInflater();
468 inflater
.inflate(R
.menu
.main_menu
, menu
);
473 public boolean onOptionsItemSelected(MenuItem item
) {
474 boolean retval
= true
;
475 switch (item
.getItemId()) {
476 case R
.id
.action_create_dir
: {
477 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
478 dialog
.show(getSupportFragmentManager(), "createdirdialog");
481 case R
.id
.action_sync_account
: {
482 startSynchronization();
485 case R
.id
.action_upload
: {
486 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
489 case R
.id
.action_settings
: {
490 Intent settingsIntent
= new Intent(this, Preferences
.class);
491 startActivity(settingsIntent
);
494 case android
.R
.id
.home
: {
495 FileFragment second
= getSecondFragment();
496 OCFile currentDir
= getCurrentDir();
497 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
498 (second
!= null
&& second
.getFile() != null
)) {
505 retval
= super.onOptionsItemSelected(item
);
510 private void startSynchronization() {
511 Log_OC
.e(TAG
, "Got to start sync");
512 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
513 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
514 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
515 Bundle bundle
= new Bundle();
516 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
517 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
518 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
519 ContentResolver
.requestSync(
521 MainApp
.getAuthority(), bundle
);
523 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
524 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
525 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
526 builder
.setExpedited(true
);
527 builder
.setManual(true
);
529 SyncRequest request
= builder
.build();
530 ContentResolver
.requestSync(request
);
536 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
537 if (itemPosition
!= 0) {
538 String targetPath
= "";
539 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
540 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
542 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
543 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
544 if (targetFolder
!= null
) {
545 browseTo(targetFolder
);
548 // the next operation triggers a new call to this method, but it's necessary to
549 // ensure that the name exposed in the action bar is the current directory when the
550 // user selected it in the navigation list
551 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
552 getSupportActionBar().setSelectedNavigationItem(0);
558 * Called, when the user selected something for uploading
560 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
561 super.onActivityResult(requestCode
, resultCode
, data
);
563 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
564 requestSimpleUpload(data
, resultCode
);
566 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
567 requestMultipleUpload(data
, resultCode
);
572 private void requestMultipleUpload(Intent data
, int resultCode
) {
573 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
574 if (filePaths
!= null
) {
575 String
[] remotePaths
= new String
[filePaths
.length
];
576 String remotePathBase
= "";
577 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
578 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
580 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
581 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
582 for (int j
= 0; j
< remotePaths
.length
; j
++) {
583 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
586 Intent i
= new Intent(this, FileUploader
.class);
587 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
588 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
589 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
590 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
591 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
592 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
596 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
597 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
604 private void requestSimpleUpload(Intent data
, int resultCode
) {
605 String filepath
= null
;
607 Uri selectedImageUri
= data
.getData();
609 String filemanagerstring
= selectedImageUri
.getPath();
610 String selectedImagePath
= getPath(selectedImageUri
);
612 if (selectedImagePath
!= null
)
613 filepath
= selectedImagePath
;
615 filepath
= filemanagerstring
;
617 } catch (Exception e
) {
618 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
622 if (filepath
== null
) {
623 Log_OC
.e(TAG
, "Couldnt resolve path to file");
624 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
630 Intent i
= new Intent(this, FileUploader
.class);
631 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
633 String remotepath
= new String();
634 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
635 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
637 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
638 remotepath
+= OCFile
.PATH_SEPARATOR
;
639 remotepath
+= new File(filepath
).getName();
641 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
642 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
643 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
644 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
645 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
650 public void onBackPressed() {
651 OCFileListFragment listOfFiles
= getListOfFilesFragment();
652 if (mDualPane
|| getSecondFragment() == null
) {
653 if (listOfFiles
!= null
) { // should never be null, indeed
654 if (mDirectories
.getCount() <= 1) {
658 int levelsUp
= listOfFiles
.onBrowseUp();
659 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
664 if (listOfFiles
!= null
) { // should never be null, indeed
665 setFile(listOfFiles
.getCurrentFile());
667 cleanSecondFragment();
672 protected void onSaveInstanceState(Bundle outState
) {
673 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
674 Log_OC
.e(TAG
, "onSaveInstanceState() start");
675 super.onSaveInstanceState(outState
);
676 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
677 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
678 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
679 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
681 Log_OC
.d(TAG
, "onSaveInstanceState() end");
687 protected void onResume() {
689 Log_OC
.e(TAG
, "onResume() start");
691 // Listen for sync messages
692 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
693 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
694 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
695 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
696 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
697 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
698 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
699 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
700 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
702 // Listen for upload messages
703 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
704 mUploadFinishReceiver
= new UploadFinishReceiver();
705 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
707 // Listen for download messages
708 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
709 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
710 mDownloadFinishReceiver
= new DownloadFinishReceiver();
711 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
713 // Listen for messages from the OperationsService
715 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
716 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
717 mOperationsServiceReceiver = new OperationsServiceReceiver();
718 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
721 Log_OC
.d(TAG
, "onResume() end");
726 protected void onPause() {
728 Log_OC
.e(TAG
, "onPause() start");
729 if (mSyncBroadcastReceiver
!= null
) {
730 unregisterReceiver(mSyncBroadcastReceiver
);
731 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
732 mSyncBroadcastReceiver
= null
;
734 if (mUploadFinishReceiver
!= null
) {
735 unregisterReceiver(mUploadFinishReceiver
);
736 mUploadFinishReceiver
= null
;
738 if (mDownloadFinishReceiver
!= null
) {
739 unregisterReceiver(mDownloadFinishReceiver
);
740 mDownloadFinishReceiver
= null
;
743 if (mOperationsServiceReceiver != null) {
744 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
745 mOperationsServiceReceiver = null;
748 Log_OC
.d(TAG
, "onPause() end");
753 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
754 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
755 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
761 protected Dialog
onCreateDialog(int id
) {
762 Dialog dialog
= null
;
763 AlertDialog
.Builder builder
;
765 case DIALOG_SHORT_WAIT
: {
766 ProgressDialog working_dialog
= new ProgressDialog(this);
767 working_dialog
.setMessage(getResources().getString(
768 R
.string
.wait_a_moment
));
769 working_dialog
.setIndeterminate(true
);
770 working_dialog
.setCancelable(false
);
771 dialog
= working_dialog
;
774 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
776 String
[] items
= null
;
778 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
779 getString(R
.string
.actionbar_upload_from_apps
),
780 getString(R
.string
.actionbar_failed_instant_upload
) };
782 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
783 getString(R
.string
.actionbar_upload_from_apps
) };
785 if (InstantUploadActivity
.IS_ENABLED
)
790 builder
= new AlertDialog
.Builder(this);
791 builder
.setTitle(R
.string
.actionbar_upload
);
792 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
793 public void onClick(DialogInterface dialog
, int item
) {
796 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
797 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
798 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
800 // TODO create and handle new fragment
801 // LocalFileListFragment
803 } else if (item
== 1) {
804 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
805 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
806 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
807 ACTION_SELECT_CONTENT_FROM_APPS
);
808 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
809 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
810 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
811 startActivity(action
);
815 dialog
= builder
.create();
818 case DIALOG_SSL_VALIDATOR
: {
819 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
822 case DIALOG_CERT_NOT_SAVED
: {
823 builder
= new AlertDialog
.Builder(this);
824 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
825 builder
.setCancelable(false
);
826 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
828 public void onClick(DialogInterface dialog
, int which
) {
832 dialog
= builder
.create();
844 * Translates a content URI of an image to a physical path
846 * @param uri The URI to resolve
847 * @return The path to the image or null if it could not be found
849 public String
getPath(Uri uri
) {
850 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
851 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
852 if (cursor
!= null
) {
853 int column_index
= cursor
854 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
855 cursor
.moveToFirst();
856 return cursor
.getString(column_index
);
862 * Pushes a directory to the drop down list
863 * @param directory to push
864 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
866 public void pushDirname(OCFile directory
) {
867 if(!directory
.isFolder()){
868 throw new IllegalArgumentException("Only directories may be pushed!");
870 mDirectories
.insert(directory
.getFileName(), 0);
875 * Pops a directory name from the drop down list
876 * @return True, unless the stack is empty
878 public boolean popDirname() {
879 mDirectories
.remove(mDirectories
.getItem(0));
880 return !mDirectories
.isEmpty();
883 // Custom array adapter to override text colors
884 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
886 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
890 public View
getView(int position
, View convertView
, ViewGroup parent
) {
891 View v
= super.getView(position
, convertView
, parent
);
893 ((TextView
) v
).setTextColor(getResources().getColorStateList(
894 android
.R
.color
.white
));
896 fixRoot((TextView
) v
);
900 public View
getDropDownView(int position
, View convertView
,
902 View v
= super.getDropDownView(position
, convertView
, parent
);
904 ((TextView
) v
).setTextColor(getResources().getColorStateList(
905 android
.R
.color
.white
));
907 fixRoot((TextView
) v
);
911 private void fixRoot(TextView v
) {
912 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
913 v
.setText(R
.string
.default_display_name_for_root_folder
);
919 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
922 * {@link BroadcastReceiver} to enable syncing feedback in UI
925 public void onReceive(Context context
, Intent intent
) {
926 String event
= intent
.getAction();
927 Log_OC
.d(TAG
, "Received broadcast " + event
);
928 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
929 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
930 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
931 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
935 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
936 mSyncInProgress
= true
;
939 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
940 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
942 if (currentDir
== null
) {
943 // current folder was removed from the server
944 Toast
.makeText( FileDisplayActivity
.this,
945 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
951 if (currentFile
== null
&& !getFile().isFolder()) {
952 // currently selected file was removed in the server, and now we know it
953 cleanSecondFragment();
954 currentFile
= currentDir
;
957 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
958 OCFileListFragment fileListFragment
= getListOfFilesFragment();
959 if (fileListFragment
!= null
) {
960 fileListFragment
.listDirectory(currentDir
);
963 setFile(currentFile
);
966 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
969 if (synchResult != null &&
970 synchResult.isSuccess() &&
971 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
972 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
974 !mRefreshSharesInProgress &&
975 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
982 removeStickyBroadcast(intent
);
983 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
984 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
987 if (synchResult
!= null
) {
988 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
989 mLastSslUntrustedServerResult
= synchResult
;
990 showDialog(DIALOG_SSL_VALIDATOR
);
997 private class UploadFinishReceiver
extends BroadcastReceiver
{
999 * Once the file upload has finished -> update view
1000 * @author David A. Velasco
1001 * {@link BroadcastReceiver} to enable upload feedback in UI
1004 public void onReceive(Context context
, Intent intent
) {
1005 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1006 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1007 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1008 OCFile currentDir
= getCurrentDir();
1009 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1010 if (sameAccount
&& isDescendant
) {
1011 refeshListOfFilesFragment();
1019 * Class waiting for broadcast events from the {@link FielDownloader} service.
1021 * Updates the UI when a download is started or finished, provided that it is relevant for the
1024 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1026 public void onReceive(Context context
, Intent intent
) {
1027 boolean sameAccount
= isSameAccount(context
, intent
);
1028 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1029 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1031 if (sameAccount
&& isDescendant
) {
1032 refeshListOfFilesFragment();
1033 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1036 if (mWaitingToSend
!= null
) {
1037 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1038 if (mWaitingToSend
.isDown() && mWaitingToSend
.getStoragePath()!=null
) {
1039 sendDownloadedFile();
1043 removeStickyBroadcast(intent
);
1046 private boolean isDescendant(String downloadedRemotePath
) {
1047 OCFile currentDir
= getCurrentDir();
1048 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1051 private boolean isSameAccount(Context context
, Intent intent
) {
1052 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1053 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1059 * Class waiting for broadcast events from the {@link OperationsService}.
1061 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1062 * operation performed in {@link OperationsService}.
1064 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1065 * probably all the operations associated to the app model.
1067 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1070 public void onReceive(Context context
, Intent intent
) {
1071 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1073 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1074 //mRefreshSharesInProgress = false;
1076 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1077 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1078 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1079 && getStorageManager() != null
1081 refeshListOfFilesFragment();
1083 if ((getSharesResult
!= null
) &&
1084 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1085 mLastSslUntrustedServerResult
= getSharesResult
;
1086 showDialog(DIALOG_SSL_VALIDATOR
);
1089 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1096 public void browseToRoot() {
1097 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1098 if (listOfFiles
!= null
) { // should never be null, indeed
1099 while (mDirectories
.getCount() > 1) {
1102 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1103 listOfFiles
.listDirectory(root
);
1104 setFile(listOfFiles
.getCurrentFile());
1105 startSyncFolderOperation(root
);
1107 cleanSecondFragment();
1111 public void browseTo(OCFile folder
) {
1112 if (folder
== null
|| !folder
.isFolder()) {
1113 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1115 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1116 if (listOfFiles
!= null
) {
1117 setNavigationListWithFolder(folder
);
1118 listOfFiles
.listDirectory(folder
);
1119 setFile(listOfFiles
.getCurrentFile());
1120 startSyncFolderOperation(folder
);
1122 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1124 cleanSecondFragment();
1131 * Updates action bar and second fragment, if in dual pane mode.
1134 public void onBrowsedDownTo(OCFile directory
) {
1135 pushDirname(directory
);
1136 cleanSecondFragment();
1139 startSyncFolderOperation(directory
);
1144 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1146 * @param file Image {@link OCFile} to show.
1149 public void startImagePreview(OCFile file
) {
1150 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1151 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1152 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1153 startActivity(showDetailsIntent
);
1157 * Stars the preview of an already down media {@link OCFile}.
1159 * @param file Media {@link OCFile} to preview.
1160 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1161 * @param autoplay When 'true', the playback will start without user interactions.
1164 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1165 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1166 setSecondFragment(mediaFragment
);
1167 updateFragmentsVisibility(true
);
1168 updateNavigationElementsInActionBar(file
);
1173 * Requests the download of the received {@link OCFile} , updates the UI
1174 * to monitor the download progress and prepares the activity to preview
1175 * or open the file when the download finishes.
1177 * @param file {@link OCFile} to download and preview.
1180 public void startDownloadForPreview(OCFile file
) {
1181 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1182 setSecondFragment(detailFragment
);
1183 mWaitingToPreview
= file
;
1184 requestForDownload();
1185 updateFragmentsVisibility(true
);
1186 updateNavigationElementsInActionBar(file
);
1192 * Shows the information of the {@link OCFile} received as a
1193 * parameter in the second fragment.
1195 * @param file {@link OCFile} whose details will be shown
1198 public void showDetails(OCFile file
) {
1199 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1200 setSecondFragment(detailFragment
);
1201 updateFragmentsVisibility(true
);
1202 updateNavigationElementsInActionBar(file
);
1210 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1211 ActionBar actionBar
= getSupportActionBar();
1212 if (chosenFile
== null
|| mDualPane
) {
1213 // only list of files - set for browsing through folders
1214 OCFile currentDir
= getCurrentDir();
1215 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1216 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1217 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1219 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1221 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1222 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1225 actionBar
.setDisplayHomeAsUpEnabled(true
);
1226 actionBar
.setDisplayShowTitleEnabled(true
);
1227 actionBar
.setTitle(chosenFile
.getFileName());
1228 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1237 public void onFileStateChanged() {
1238 refeshListOfFilesFragment();
1239 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1247 public FileDownloaderBinder
getFileDownloaderBinder() {
1248 return mDownloaderBinder
;
1256 public FileUploaderBinder
getFileUploaderBinder() {
1257 return mUploaderBinder
;
1261 /** Defines callbacks for service binding, passed to bindService() */
1262 private class ListServiceConnection
implements ServiceConnection
{
1265 public void onServiceConnected(ComponentName component
, IBinder service
) {
1266 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1267 Log_OC
.d(TAG
, "Download service connected");
1268 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1269 if (mWaitingToPreview
!= null
) {
1270 requestForDownload();
1273 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1274 Log_OC
.d(TAG
, "Upload service connected");
1275 mUploaderBinder
= (FileUploaderBinder
) service
;
1279 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1280 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1281 if (listOfFiles
!= null
) {
1282 listOfFiles
.listDirectory();
1284 FileFragment secondFragment
= getSecondFragment();
1285 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1286 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1287 detailFragment
.listenForTransferProgress();
1288 detailFragment
.updateFileDetails(false
, false
);
1293 public void onServiceDisconnected(ComponentName component
) {
1294 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1295 Log_OC
.d(TAG
, "Download service disconnected");
1296 mDownloaderBinder
= null
;
1297 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1298 Log_OC
.d(TAG
, "Upload service disconnected");
1299 mUploaderBinder
= null
;
1307 * Launch an intent to request the PIN code to the user before letting him use the app
1309 private void requestPinCode() {
1310 boolean pinStart
= false
;
1311 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1312 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1314 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1315 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1322 public void onSavedCertificate() {
1323 startSyncFolderOperation(getCurrentDir());
1328 public void onFailedSavingCertificate() {
1329 showDialog(DIALOG_CERT_NOT_SAVED
);
1334 * Updates the view associated to the activity after the finish of some operation over files
1335 * in the current account.
1337 * @param operation Removal operation performed.
1338 * @param result Result of the removal.
1341 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1342 super.onRemoteOperationFinish(operation
, result
);
1344 if (operation
instanceof RemoveFileOperation
) {
1345 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1347 } else if (operation
instanceof RenameFileOperation
) {
1348 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1350 } else if (operation
instanceof SynchronizeFileOperation
) {
1351 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1353 } else if (operation
instanceof CreateFolderOperation
) {
1354 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1356 } else if (operation
instanceof CreateShareOperation
) {
1357 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1359 } else if (operation
instanceof UnshareLinkOperation
) {
1360 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1367 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1368 if (result
.isSuccess()) {
1369 refreshShowDetails();
1370 refeshListOfFilesFragment();
1375 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1376 if (result
.isSuccess()) {
1377 refreshShowDetails();
1378 refeshListOfFilesFragment();
1379 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1380 cleanSecondFragment();
1381 refeshListOfFilesFragment();
1385 private void refreshShowDetails() {
1386 FileFragment details
= getSecondFragment();
1387 if (details
!= null
) {
1388 OCFile file
= details
.getFile();
1390 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1391 if (details
instanceof PreviewMediaFragment
) {
1392 // Refresh OCFile of the fragment
1393 ((PreviewMediaFragment
) details
).updateFile(file
);
1398 invalidateOptionsMenu();
1403 * Updates the view associated to the activity after the finish of an operation trying to remove a
1406 * @param operation Removal operation performed.
1407 * @param result Result of the removal.
1409 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1410 dismissLoadingDialog();
1411 if (result
.isSuccess()) {
1412 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1414 OCFile removedFile
= operation
.getFile();
1415 getSecondFragment();
1416 FileFragment second
= getSecondFragment();
1417 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1418 cleanSecondFragment();
1420 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1421 refeshListOfFilesFragment();
1425 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1427 if (result
.isSslRecoverableException()) {
1428 mLastSslUntrustedServerResult
= result
;
1429 showDialog(DIALOG_SSL_VALIDATOR
);
1435 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1437 * @param operation Creation operation performed.
1438 * @param result Result of the creation.
1440 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1441 if (result
.isSuccess()) {
1442 dismissLoadingDialog();
1443 refeshListOfFilesFragment();
1446 dismissLoadingDialog();
1447 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1448 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1451 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1454 } catch (NotFoundException e
) {
1455 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1463 * Updates the view associated to the activity after the finish of an operation trying to rename a
1466 * @param operation Renaming operation performed.
1467 * @param result Result of the renaming.
1469 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1470 dismissLoadingDialog();
1471 OCFile renamedFile
= operation
.getFile();
1472 if (result
.isSuccess()) {
1474 FileFragment details
= getSecondFragment();
1475 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1476 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1479 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1480 refeshListOfFilesFragment();
1484 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1485 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1487 // TODO throw again the new rename dialog
1488 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1489 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1492 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1494 if (result
.isSslRecoverableException()) {
1495 mLastSslUntrustedServerResult
= result
;
1496 showDialog(DIALOG_SSL_VALIDATOR
);
1503 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1504 dismissLoadingDialog();
1505 OCFile syncedFile
= operation
.getLocalFile();
1506 if (!result
.isSuccess()) {
1507 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1508 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1509 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1510 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1516 if (operation
.transferWasRequested()) {
1517 refeshListOfFilesFragment();
1518 onTransferStateChanged(syncedFile
, true
, true
);
1521 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1532 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1534 FileFragment details
= getSecondFragment();
1535 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1536 if (downloading
|| uploading
) {
1537 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1539 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1546 public void onDismiss(EditNameDialog dialog
) {
1547 if (dialog
.getResult()) {
1548 String newDirectoryName
= dialog
.getNewFilename().trim();
1549 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1550 if (newDirectoryName
.length() > 0) {
1551 String path
= getCurrentDir().getRemotePath();
1554 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1555 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1556 operation
.execute( getAccount(),
1557 FileDisplayActivity
.this,
1558 FileDisplayActivity
.this,
1560 FileDisplayActivity
.this);
1562 showLoadingDialog();
1568 private void requestForDownload() {
1569 Account account
= getAccount();
1570 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1571 Intent i
= new Intent(this, FileDownloader
.class);
1572 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1573 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1579 private OCFile
getCurrentDir() {
1580 OCFile file
= getFile();
1582 if (file
.isFolder()) {
1584 } else if (getStorageManager() != null
) {
1585 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1586 return getStorageManager().getFileByPath(parentPath
);
1592 public void startSyncFolderOperation(OCFile folder
) {
1593 long currentSyncTime
= System
.currentTimeMillis();
1595 mSyncInProgress
= true
;
1597 // perform folder synchronization
1598 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1601 getFileOperationsHelper().isSharedSupported(this),
1602 getStorageManager(),
1604 getApplicationContext()
1606 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1608 setSupportProgressBarIndeterminateVisibility(true
);
1612 private void startGetShares() {
1613 // Get shared files/folders
1614 Intent intent = new Intent(this, OperationsService.class);
1615 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1616 startService(intent);
1618 mRefreshSharesInProgress = true;
1623 * Requests the download of the received {@link OCFile} , updates the UI
1624 * to monitor the download progress and prepares the activity to send the file
1625 * when the download finishes.
1627 * @param file {@link OCFile} to download and preview.
1630 public void startDownloadForSending(OCFile file
) {
1631 mWaitingToSend
= file
;
1632 requestForDownload(mWaitingToSend
);
1633 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1634 updateFragmentsVisibility(hasSecondFragment
);
1637 private void requestForDownload(OCFile file
) {
1638 Account account
= getAccount();
1639 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1640 Intent i
= new Intent(this, FileDownloader
.class);
1641 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1642 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1647 private void sendDownloadedFile(){
1648 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1649 mWaitingToSend
= null
;