1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.Dialog
;
26 import android
.app
.ProgressDialog
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.ComponentName
;
29 import android
.content
.ContentResolver
;
30 import android
.content
.Context
;
31 import android
.content
.DialogInterface
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.content
.SyncRequest
;
37 import android
.content
.res
.Resources
.NotFoundException
;
38 import android
.database
.Cursor
;
39 import android
.net
.Uri
;
40 import android
.os
.Bundle
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.provider
.MediaStore
;
44 import android
.support
.v4
.app
.Fragment
;
45 import android
.support
.v4
.app
.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
.operations
.common
.RemoteOperation
;
71 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
72 import com
.owncloud
.android
.lib
.operations
.common
.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
.EditNameDialog
.EditNameDialogListener
;
83 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
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
.PreviewImageFragment
;
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";
125 public static final int DIALOG_SHORT_WAIT
= 0;
126 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
127 private static final int DIALOG_SSL_VALIDATOR
= 2;
128 private static final int DIALOG_CERT_NOT_SAVED
= 3;
130 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;
146 protected void onCreate(Bundle savedInstanceState
) {
147 Log_OC
.d(TAG
, "onCreate() start");
148 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
150 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
152 /// bindings to transference services
153 mUploadConnection
= new ListServiceConnection();
154 mDownloadConnection
= new ListServiceConnection();
155 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
156 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
158 // PIN CODE request ; best location is to decide, let's try this first
159 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
161 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
166 Intent observer_intent
= new Intent(this, FileObserverService
.class);
167 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
168 startService(observer_intent
);
170 /// Load of saved instance state
171 if(savedInstanceState
!= null
) {
172 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
173 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
174 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
177 mWaitingToPreview
= null
;
178 mSyncInProgress
= false
;
179 //mRefreshSharesInProgress = false;
184 // Inflate and set the layout view
185 setContentView(R
.layout
.files
);
186 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
187 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
188 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
189 if (savedInstanceState
== null
) {
190 createMinFragments();
192 Log_OC
.d(TAG
, "Init the secondFragment again");
194 initFragmentsWithFile();
199 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
200 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
201 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
203 Log_OC
.d(TAG
, "onCreate() end");
207 protected void onStart() {
209 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
213 protected void onDestroy() {
215 if (mDownloadConnection
!= null
)
216 unbindService(mDownloadConnection
);
217 if (mUploadConnection
!= null
)
218 unbindService(mUploadConnection
);
223 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
226 protected void onAccountSet(boolean stateWasRecovered
) {
227 super.onAccountSet(stateWasRecovered
);
228 if (getAccount() != null
) {
229 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
230 OCFile file
= getFile();
231 // get parent from path
232 String parentPath
= "";
234 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
235 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
236 // get parent from path
237 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
238 if (getStorageManager().getFileByPath(parentPath
) == null
)
239 file
= null
; // not able to know the directory where the file is uploading
241 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
245 // fall back to root folder
246 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
249 setNavigationListWithFolder(file
);
251 if (!stateWasRecovered
) {
252 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
253 initFragmentsWithFile();
254 if (file
.isFolder()) {
255 startSyncFolderOperation(file
);
259 updateFragmentsVisibility(!file
.isFolder());
260 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
266 private void setNavigationListWithFolder(OCFile file
) {
267 mDirectories
.clear();
268 OCFile fileIt
= file
;
270 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
271 if (fileIt
.isFolder()) {
272 mDirectories
.add(fileIt
.getFileName());
274 // get parent from path
275 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
276 fileIt
= getStorageManager().getFileByPath(parentPath
);
278 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
282 private void createMinFragments() {
283 OCFileListFragment listOfFiles
= new OCFileListFragment();
284 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
285 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
286 transaction
.commit();
289 private void initFragmentsWithFile() {
290 if (getAccount() != null
&& getFile() != null
) {
292 OCFileListFragment listOfFiles
= getListOfFilesFragment();
293 if (listOfFiles
!= null
) {
294 listOfFiles
.listDirectory(getCurrentDir());
296 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
300 OCFile file
= getFile();
301 Fragment secondFragment
= chooseInitialSecondFragment(file
);
302 if (secondFragment
!= null
) {
303 setSecondFragment(secondFragment
);
304 updateFragmentsVisibility(true
);
305 updateNavigationElementsInActionBar(file
);
308 cleanSecondFragment();
312 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
313 if (getAccount() == null
) {
314 Log
.wtf(TAG
, "\t account is NULL");
316 if (getFile() == null
) {
317 Log
.wtf(TAG
, "\t file is NULL");
322 private Fragment
chooseInitialSecondFragment(OCFile file
) {
323 Fragment secondFragment
= null
;
324 if (file
!= null
&& !file
.isFolder()) {
325 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
326 && file
.getLastSyncDateForProperties() > 0 // temporal fix
328 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
329 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
330 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
333 secondFragment
= new FileDetailFragment(file
, getAccount());
336 return secondFragment
;
341 * Replaces the second fragment managed by the activity with the received as
344 * Assumes never will be more than two fragments managed at the same time.
346 * @param fragment New second Fragment to set.
348 private void setSecondFragment(Fragment fragment
) {
349 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
350 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
351 transaction
.commit();
355 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
357 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
360 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
361 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
364 } else if (existsSecondFragment
) {
365 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
366 mLeftFragmentContainer
.setVisibility(View
.GONE
);
368 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
376 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
377 mRightFragmentContainer
.setVisibility(View
.GONE
);
383 private OCFileListFragment
getListOfFilesFragment() {
384 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
385 if (listOfFiles
!= null
) {
386 return (OCFileListFragment
)listOfFiles
;
388 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
392 protected FileFragment
getSecondFragment() {
393 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
394 if (second
!= null
) {
395 return (FileFragment
)second
;
400 public void cleanSecondFragment() {
401 Fragment second
= getSecondFragment();
402 if (second
!= null
) {
403 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
407 updateFragmentsVisibility(false
);
408 updateNavigationElementsInActionBar(null
);
411 protected void refeshListOfFilesFragment() {
412 OCFileListFragment fileListFragment
= getListOfFilesFragment();
413 if (fileListFragment
!= null
) {
414 fileListFragment
.listDirectory();
418 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
419 FileFragment secondFragment
= getSecondFragment();
420 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
421 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
422 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
423 OCFile fileInFragment
= detailsFragment
.getFile();
424 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
425 // the user browsed to other file ; forget the automatic preview
426 mWaitingToPreview
= null
;
428 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
429 // grant that the right panel updates the progress bar
430 detailsFragment
.listenForTransferProgress();
431 detailsFragment
.updateFileDetails(true
, false
);
433 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
434 // update the right panel
435 boolean detailsFragmentChanged
= false
;
438 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
439 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
440 startMediaPreview(mWaitingToPreview
, 0, true
);
441 detailsFragmentChanged
= true
;
443 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
446 mWaitingToPreview
= null
;
448 if (!detailsFragmentChanged
) {
449 detailsFragment
.updateFileDetails(false
, (success
));
456 public boolean onCreateOptionsMenu(Menu menu
) {
457 MenuInflater inflater
= getSherlock().getMenuInflater();
458 inflater
.inflate(R
.menu
.main_menu
, menu
);
463 public boolean onOptionsItemSelected(MenuItem item
) {
464 boolean retval
= true
;
465 switch (item
.getItemId()) {
466 case R
.id
.action_create_dir
: {
467 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
468 dialog
.show(getSupportFragmentManager(), "createdirdialog");
471 case R
.id
.action_sync_account
: {
472 startSynchronization();
475 case R
.id
.action_upload
: {
476 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
479 case R
.id
.action_settings
: {
480 Intent settingsIntent
= new Intent(this, Preferences
.class);
481 startActivity(settingsIntent
);
484 case android
.R
.id
.home
: {
485 FileFragment second
= getSecondFragment();
486 OCFile currentDir
= getCurrentDir();
487 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
488 (second
!= null
&& second
.getFile() != null
)) {
495 retval
= super.onOptionsItemSelected(item
);
500 private void startSynchronization() {
501 Log_OC
.e(TAG
, "Got to start sync");
502 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
503 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
504 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
505 Bundle bundle
= new Bundle();
506 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
507 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
508 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
509 ContentResolver
.requestSync(
511 MainApp
.getAuthority(), bundle
);
513 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
514 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
515 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
516 builder
.setExpedited(true
);
517 builder
.setManual(true
);
519 SyncRequest request
= builder
.build();
520 ContentResolver
.requestSync(request
);
526 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
527 if (itemPosition
!= 0) {
528 String targetPath
= "";
529 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
530 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
532 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
533 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
534 if (targetFolder
!= null
) {
535 browseTo(targetFolder
);
538 // the next operation triggers a new call to this method, but it's necessary to
539 // ensure that the name exposed in the action bar is the current directory when the
540 // user selected it in the navigation list
541 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
542 getSupportActionBar().setSelectedNavigationItem(0);
548 * Called, when the user selected something for uploading
550 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
551 super.onActivityResult(requestCode
, resultCode
, data
);
553 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
554 requestSimpleUpload(data
, resultCode
);
556 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
557 requestMultipleUpload(data
, resultCode
);
562 private void requestMultipleUpload(Intent data
, int resultCode
) {
563 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
564 if (filePaths
!= null
) {
565 String
[] remotePaths
= new String
[filePaths
.length
];
566 String remotePathBase
= "";
567 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
568 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
570 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
571 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
572 for (int j
= 0; j
< remotePaths
.length
; j
++) {
573 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
576 Intent i
= new Intent(this, FileUploader
.class);
577 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
578 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
579 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
580 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
581 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
582 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
586 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
587 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
594 private void requestSimpleUpload(Intent data
, int resultCode
) {
595 String filepath
= null
;
597 Uri selectedImageUri
= data
.getData();
599 String filemanagerstring
= selectedImageUri
.getPath();
600 String selectedImagePath
= getPath(selectedImageUri
);
602 if (selectedImagePath
!= null
)
603 filepath
= selectedImagePath
;
605 filepath
= filemanagerstring
;
607 } catch (Exception e
) {
608 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
612 if (filepath
== null
) {
613 Log_OC
.e(TAG
, "Couldnt resolve path to file");
614 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
620 Intent i
= new Intent(this, FileUploader
.class);
621 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
623 String remotepath
= new String();
624 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
625 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
627 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
628 remotepath
+= OCFile
.PATH_SEPARATOR
;
629 remotepath
+= new File(filepath
).getName();
631 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
632 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
633 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
634 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
635 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
640 public void onBackPressed() {
641 OCFileListFragment listOfFiles
= getListOfFilesFragment();
642 if (mDualPane
|| getSecondFragment() == null
) {
643 if (listOfFiles
!= null
) { // should never be null, indeed
644 if (mDirectories
.getCount() <= 1) {
648 int levelsUp
= listOfFiles
.onBrowseUp();
649 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
654 if (listOfFiles
!= null
) { // should never be null, indeed
655 setFile(listOfFiles
.getCurrentFile());
657 cleanSecondFragment();
662 protected void onSaveInstanceState(Bundle outState
) {
663 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
664 Log_OC
.e(TAG
, "onSaveInstanceState() start");
665 super.onSaveInstanceState(outState
);
666 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
667 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
668 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
670 Log_OC
.d(TAG
, "onSaveInstanceState() end");
676 protected void onResume() {
678 Log_OC
.e(TAG
, "onResume() start");
680 // Listen for sync messages
681 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
682 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
683 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED
);
684 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
685 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
686 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
687 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
688 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
689 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
691 // Listen for upload messages
692 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
693 mUploadFinishReceiver
= new UploadFinishReceiver();
694 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
696 // Listen for download messages
697 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
698 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
699 mDownloadFinishReceiver
= new DownloadFinishReceiver();
700 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
702 // Listen for messages from the OperationsService
704 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
705 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
706 mOperationsServiceReceiver = new OperationsServiceReceiver();
707 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
710 Log_OC
.d(TAG
, "onResume() end");
715 protected void onPause() {
717 Log_OC
.e(TAG
, "onPause() start");
718 if (mSyncBroadcastReceiver
!= null
) {
719 unregisterReceiver(mSyncBroadcastReceiver
);
720 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
721 mSyncBroadcastReceiver
= null
;
723 if (mUploadFinishReceiver
!= null
) {
724 unregisterReceiver(mUploadFinishReceiver
);
725 mUploadFinishReceiver
= null
;
727 if (mDownloadFinishReceiver
!= null
) {
728 unregisterReceiver(mDownloadFinishReceiver
);
729 mDownloadFinishReceiver
= null
;
732 if (mOperationsServiceReceiver != null) {
733 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
734 mOperationsServiceReceiver = null;
737 Log_OC
.d(TAG
, "onPause() end");
742 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
743 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
744 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
750 protected Dialog
onCreateDialog(int id
) {
751 Dialog dialog
= null
;
752 AlertDialog
.Builder builder
;
754 case DIALOG_SHORT_WAIT
: {
755 ProgressDialog working_dialog
= new ProgressDialog(this);
756 working_dialog
.setMessage(getResources().getString(
757 R
.string
.wait_a_moment
));
758 working_dialog
.setIndeterminate(true
);
759 working_dialog
.setCancelable(false
);
760 dialog
= working_dialog
;
763 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
765 String
[] items
= null
;
767 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
768 getString(R
.string
.actionbar_upload_from_apps
),
769 getString(R
.string
.actionbar_failed_instant_upload
) };
771 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
772 getString(R
.string
.actionbar_upload_from_apps
) };
774 if (InstantUploadActivity
.IS_ENABLED
)
779 builder
= new AlertDialog
.Builder(this);
780 builder
.setTitle(R
.string
.actionbar_upload
);
781 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
782 public void onClick(DialogInterface dialog
, int item
) {
785 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
786 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
787 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
789 // TODO create and handle new fragment
790 // LocalFileListFragment
792 } else if (item
== 1) {
793 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
794 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
795 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
796 ACTION_SELECT_CONTENT_FROM_APPS
);
797 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
798 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
799 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
800 startActivity(action
);
804 dialog
= builder
.create();
807 case DIALOG_SSL_VALIDATOR
: {
808 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
811 case DIALOG_CERT_NOT_SAVED
: {
812 builder
= new AlertDialog
.Builder(this);
813 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
814 builder
.setCancelable(false
);
815 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
817 public void onClick(DialogInterface dialog
, int which
) {
821 dialog
= builder
.create();
833 * Translates a content URI of an image to a physical path
835 * @param uri The URI to resolve
836 * @return The path to the image or null if it could not be found
838 public String
getPath(Uri uri
) {
839 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
840 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
841 if (cursor
!= null
) {
842 int column_index
= cursor
843 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
844 cursor
.moveToFirst();
845 return cursor
.getString(column_index
);
851 * Pushes a directory to the drop down list
852 * @param directory to push
853 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
855 public void pushDirname(OCFile directory
) {
856 if(!directory
.isFolder()){
857 throw new IllegalArgumentException("Only directories may be pushed!");
859 mDirectories
.insert(directory
.getFileName(), 0);
864 * Pops a directory name from the drop down list
865 * @return True, unless the stack is empty
867 public boolean popDirname() {
868 mDirectories
.remove(mDirectories
.getItem(0));
869 return !mDirectories
.isEmpty();
872 // Custom array adapter to override text colors
873 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
875 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
879 public View
getView(int position
, View convertView
, ViewGroup parent
) {
880 View v
= super.getView(position
, convertView
, parent
);
882 ((TextView
) v
).setTextColor(getResources().getColorStateList(
883 android
.R
.color
.white
));
885 fixRoot((TextView
) v
);
889 public View
getDropDownView(int position
, View convertView
,
891 View v
= super.getDropDownView(position
, convertView
, parent
);
893 ((TextView
) v
).setTextColor(getResources().getColorStateList(
894 android
.R
.color
.white
));
896 fixRoot((TextView
) v
);
900 private void fixRoot(TextView v
) {
901 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
902 v
.setText(R
.string
.default_display_name_for_root_folder
);
908 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
911 * {@link BroadcastReceiver} to enable syncing feedback in UI
914 public void onReceive(Context context
, Intent intent
) {
915 String event
= intent
.getAction();
916 Log_OC
.d(TAG
, "Received broadcast " + event
);
917 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
918 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
919 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
920 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
924 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
925 mSyncInProgress
= true
;
928 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
929 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
931 if (currentDir
== null
) {
932 // current folder was removed from the server
933 Toast
.makeText( FileDisplayActivity
.this,
934 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
940 if (currentFile
== null
&& !getFile().isFolder()) {
941 // currently selected file was removed in the server, and now we know it
942 cleanSecondFragment();
943 currentFile
= currentDir
;
946 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
947 OCFileListFragment fileListFragment
= getListOfFilesFragment();
948 if (fileListFragment
!= null
) {
949 fileListFragment
.listDirectory(currentDir
);
952 setFile(currentFile
);
955 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
958 if (synchResult != null &&
959 synchResult.isSuccess() &&
960 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
961 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
963 !mRefreshSharesInProgress &&
964 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
971 removeStickyBroadcast(intent
);
972 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
973 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
976 if (synchResult
!= null
) {
977 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
978 mLastSslUntrustedServerResult
= synchResult
;
979 showDialog(DIALOG_SSL_VALIDATOR
);
986 private class UploadFinishReceiver
extends BroadcastReceiver
{
988 * Once the file upload has finished -> update view
989 * @author David A. Velasco
990 * {@link BroadcastReceiver} to enable upload feedback in UI
993 public void onReceive(Context context
, Intent intent
) {
994 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
995 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
996 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
997 OCFile currentDir
= getCurrentDir();
998 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
999 if (sameAccount
&& isDescendant
) {
1000 refeshListOfFilesFragment();
1008 * Class waiting for broadcast events from the {@link FielDownloader} service.
1010 * Updates the UI when a download is started or finished, provided that it is relevant for the
1013 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1015 public void onReceive(Context context
, Intent intent
) {
1016 boolean sameAccount
= isSameAccount(context
, intent
);
1017 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1018 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1020 if (sameAccount
&& isDescendant
) {
1021 refeshListOfFilesFragment();
1022 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1025 removeStickyBroadcast(intent
);
1028 private boolean isDescendant(String downloadedRemotePath
) {
1029 OCFile currentDir
= getCurrentDir();
1030 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1033 private boolean isSameAccount(Context context
, Intent intent
) {
1034 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1035 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1041 * Class waiting for broadcast events from the {@link OperationsService}.
1043 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1044 * operation performed in {@link OperationsService}.
1046 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1047 * probably all the operations associated to the app model.
1049 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1052 public void onReceive(Context context
, Intent intent
) {
1053 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1055 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1056 //mRefreshSharesInProgress = false;
1058 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1059 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1060 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1061 && getStorageManager() != null
1063 refeshListOfFilesFragment();
1065 if ((getSharesResult
!= null
) &&
1066 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1067 mLastSslUntrustedServerResult
= getSharesResult
;
1068 showDialog(DIALOG_SSL_VALIDATOR
);
1071 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1078 public void browseToRoot() {
1079 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1080 if (listOfFiles
!= null
) { // should never be null, indeed
1081 while (mDirectories
.getCount() > 1) {
1084 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1085 listOfFiles
.listDirectory(root
);
1086 setFile(listOfFiles
.getCurrentFile());
1087 startSyncFolderOperation(root
);
1089 cleanSecondFragment();
1093 public void browseTo(OCFile folder
) {
1094 if (folder
== null
|| !folder
.isFolder()) {
1095 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1097 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1098 if (listOfFiles
!= null
) {
1099 setNavigationListWithFolder(folder
);
1100 listOfFiles
.listDirectory(folder
);
1101 setFile(listOfFiles
.getCurrentFile());
1102 startSyncFolderOperation(folder
);
1104 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1106 cleanSecondFragment();
1113 * Updates action bar and second fragment, if in dual pane mode.
1116 public void onBrowsedDownTo(OCFile directory
) {
1117 pushDirname(directory
);
1118 cleanSecondFragment();
1121 startSyncFolderOperation(directory
);
1126 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1128 * @param file Image {@link OCFile} to show.
1131 public void startImagePreview(OCFile file
) {
1132 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1133 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1134 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1135 startActivity(showDetailsIntent
);
1139 * Stars the preview of an already down media {@link OCFile}.
1141 * @param file Media {@link OCFile} to preview.
1142 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1143 * @param autoplay When 'true', the playback will start without user interactions.
1146 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1147 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1148 setSecondFragment(mediaFragment
);
1149 updateFragmentsVisibility(true
);
1150 updateNavigationElementsInActionBar(file
);
1155 * Requests the download of the received {@link OCFile} , updates the UI
1156 * to monitor the download progress and prepares the activity to preview
1157 * or open the file when the download finishes.
1159 * @param file {@link OCFile} to download and preview.
1162 public void startDownloadForPreview(OCFile file
) {
1163 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1164 setSecondFragment(detailFragment
);
1165 mWaitingToPreview
= file
;
1166 requestForDownload();
1167 updateFragmentsVisibility(true
);
1168 updateNavigationElementsInActionBar(file
);
1174 * Shows the information of the {@link OCFile} received as a
1175 * parameter in the second fragment.
1177 * @param file {@link OCFile} whose details will be shown
1180 public void showDetails(OCFile file
) {
1181 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1182 setSecondFragment(detailFragment
);
1183 updateFragmentsVisibility(true
);
1184 updateNavigationElementsInActionBar(file
);
1192 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1193 ActionBar actionBar
= getSupportActionBar();
1194 if (chosenFile
== null
|| mDualPane
) {
1195 // only list of files - set for browsing through folders
1196 OCFile currentDir
= getCurrentDir();
1197 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1198 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1199 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1201 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1203 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1204 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1207 actionBar
.setDisplayHomeAsUpEnabled(true
);
1208 actionBar
.setDisplayShowTitleEnabled(true
);
1209 actionBar
.setTitle(chosenFile
.getFileName());
1210 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1219 public void onFileStateChanged() {
1220 refeshListOfFilesFragment();
1221 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1229 public FileDownloaderBinder
getFileDownloaderBinder() {
1230 return mDownloaderBinder
;
1238 public FileUploaderBinder
getFileUploaderBinder() {
1239 return mUploaderBinder
;
1243 /** Defines callbacks for service binding, passed to bindService() */
1244 private class ListServiceConnection
implements ServiceConnection
{
1247 public void onServiceConnected(ComponentName component
, IBinder service
) {
1248 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1249 Log_OC
.d(TAG
, "Download service connected");
1250 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1251 if (mWaitingToPreview
!= null
) {
1252 requestForDownload();
1255 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1256 Log_OC
.d(TAG
, "Upload service connected");
1257 mUploaderBinder
= (FileUploaderBinder
) service
;
1261 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1262 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1263 if (listOfFiles
!= null
) {
1264 listOfFiles
.listDirectory();
1266 FileFragment secondFragment
= getSecondFragment();
1267 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1268 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1269 detailFragment
.listenForTransferProgress();
1270 detailFragment
.updateFileDetails(false
, false
);
1275 public void onServiceDisconnected(ComponentName component
) {
1276 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1277 Log_OC
.d(TAG
, "Download service disconnected");
1278 mDownloaderBinder
= null
;
1279 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1280 Log_OC
.d(TAG
, "Upload service disconnected");
1281 mUploaderBinder
= null
;
1289 * Launch an intent to request the PIN code to the user before letting him use the app
1291 private void requestPinCode() {
1292 boolean pinStart
= false
;
1293 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1294 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1296 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1297 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1304 public void onSavedCertificate() {
1305 startSyncFolderOperation(getCurrentDir());
1310 public void onFailedSavingCertificate() {
1311 showDialog(DIALOG_CERT_NOT_SAVED
);
1316 * Updates the view associated to the activity after the finish of some operation over files
1317 * in the current account.
1319 * @param operation Removal operation performed.
1320 * @param result Result of the removal.
1323 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1324 super.onRemoteOperationFinish(operation
, result
);
1326 if (operation
instanceof RemoveFileOperation
) {
1327 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1329 } else if (operation
instanceof RenameFileOperation
) {
1330 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1332 } else if (operation
instanceof SynchronizeFileOperation
) {
1333 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1335 } else if (operation
instanceof CreateFolderOperation
) {
1336 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1338 } else if (operation
instanceof CreateShareOperation
) {
1339 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1341 } else if (operation
instanceof UnshareLinkOperation
) {
1342 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1349 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1350 if (result
.isSuccess()) {
1351 OCFile file
= getStorageManager().getFileByPath(getFile().getRemotePath());
1355 refreshShowDetails();
1356 refeshListOfFilesFragment();
1361 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1362 if (result
.isSuccess()) {
1363 OCFile file
= getStorageManager().getFileByPath(getFile().getRemotePath());
1367 refreshShowDetails();
1368 refeshListOfFilesFragment();
1369 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1370 cleanSecondFragment();
1371 refeshListOfFilesFragment();
1375 private void refreshShowDetails() {
1376 FileFragment details
= getSecondFragment();
1377 if (details
!= null
) {
1378 OCFile file
= details
.getFile();
1380 file
= getStorageManager().getFileByPath(file
.getRemotePath()); {
1381 if (!(details
instanceof PreviewMediaFragment
|| details
instanceof PreviewImageFragment
)) {
1383 } else if (details
instanceof PreviewMediaFragment
) {
1384 startMediaPreview(file
, 0, false
);
1387 invalidateOptionsMenu();
1393 * Updates the view associated to the activity after the finish of an operation trying to remove a
1396 * @param operation Removal operation performed.
1397 * @param result Result of the removal.
1399 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1400 dismissLoadingDialog();
1401 if (result
.isSuccess()) {
1402 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1404 OCFile removedFile
= operation
.getFile();
1405 getSecondFragment();
1406 FileFragment second
= getSecondFragment();
1407 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1408 cleanSecondFragment();
1410 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1411 refeshListOfFilesFragment();
1415 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1417 if (result
.isSslRecoverableException()) {
1418 mLastSslUntrustedServerResult
= result
;
1419 showDialog(DIALOG_SSL_VALIDATOR
);
1425 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1427 * @param operation Creation operation performed.
1428 * @param result Result of the creation.
1430 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1431 if (result
.isSuccess()) {
1432 dismissLoadingDialog();
1433 refeshListOfFilesFragment();
1436 dismissLoadingDialog();
1437 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1438 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1441 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1444 } catch (NotFoundException e
) {
1445 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1453 * Updates the view associated to the activity after the finish of an operation trying to rename a
1456 * @param operation Renaming operation performed.
1457 * @param result Result of the renaming.
1459 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1460 dismissLoadingDialog();
1461 OCFile renamedFile
= operation
.getFile();
1462 if (result
.isSuccess()) {
1464 FileFragment details
= getSecondFragment();
1465 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1466 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1469 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1470 refeshListOfFilesFragment();
1474 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1475 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1477 // TODO throw again the new rename dialog
1478 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1479 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1482 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1484 if (result
.isSslRecoverableException()) {
1485 mLastSslUntrustedServerResult
= result
;
1486 showDialog(DIALOG_SSL_VALIDATOR
);
1493 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1494 dismissLoadingDialog();
1495 OCFile syncedFile
= operation
.getLocalFile();
1496 if (!result
.isSuccess()) {
1497 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1498 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1499 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1500 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1506 if (operation
.transferWasRequested()) {
1507 refeshListOfFilesFragment();
1508 onTransferStateChanged(syncedFile
, true
, true
);
1511 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1522 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1524 FileFragment details
= getSecondFragment();
1525 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1526 if (downloading
|| uploading
) {
1527 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1529 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1536 public void onDismiss(EditNameDialog dialog
) {
1537 if (dialog
.getResult()) {
1538 String newDirectoryName
= dialog
.getNewFilename().trim();
1539 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1540 if (newDirectoryName
.length() > 0) {
1541 String path
= getCurrentDir().getRemotePath();
1544 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1545 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1546 operation
.execute( getAccount(),
1547 FileDisplayActivity
.this,
1548 FileDisplayActivity
.this,
1550 FileDisplayActivity
.this);
1552 showLoadingDialog();
1558 private void requestForDownload() {
1559 Account account
= getAccount();
1560 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1561 Intent i
= new Intent(this, FileDownloader
.class);
1562 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1563 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1569 private OCFile
getCurrentDir() {
1570 OCFile file
= getFile();
1572 if (file
.isFolder()) {
1574 } else if (getStorageManager() != null
) {
1575 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1576 return getStorageManager().getFileByPath(parentPath
);
1582 public void startSyncFolderOperation(OCFile folder
) {
1583 long currentSyncTime
= System
.currentTimeMillis();
1585 mSyncInProgress
= true
;
1587 // perform folder synchronization
1588 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1591 getFileOperationsHelper().isSharedSupported(this),
1592 getStorageManager(),
1594 getApplicationContext()
1596 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1598 setSupportProgressBarIndeterminateVisibility(true
);
1602 private void startGetShares() {
1603 // Get shared files/folders
1604 Intent intent = new Intent(this, OperationsService.class);
1605 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1606 startService(intent);
1608 mRefreshSharesInProgress = true;