1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.Dialog
;
26 import android
.app
.ProgressDialog
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.ComponentName
;
29 import android
.content
.ContentResolver
;
30 import android
.content
.Context
;
31 import android
.content
.DialogInterface
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.content
.SyncRequest
;
37 import android
.content
.res
.Resources
.NotFoundException
;
38 import android
.database
.Cursor
;
39 import android
.net
.Uri
;
40 import android
.os
.Bundle
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.provider
.MediaStore
;
44 import android
.support
.v4
.app
.Fragment
;
45 import android
.support
.v4
.app
.FragmentManager
;
46 import android
.support
.v4
.app
.FragmentTransaction
;
47 //import android.support.v4.content.LocalBroadcastManager;
48 import android
.util
.Log
;
49 import android
.view
.View
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ArrayAdapter
;
52 import android
.widget
.TextView
;
53 import android
.widget
.Toast
;
55 import com
.actionbarsherlock
.app
.ActionBar
;
56 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
57 import com
.actionbarsherlock
.view
.Menu
;
58 import com
.actionbarsherlock
.view
.MenuInflater
;
59 import com
.actionbarsherlock
.view
.MenuItem
;
60 import com
.actionbarsherlock
.view
.Window
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileObserverService
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
71 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
75 import com
.owncloud
.android
.operations
.CreateShareOperation
;
76 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
77 import com
.owncloud
.android
.operations
.RenameFileOperation
;
78 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
79 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
80 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
81 import com
.owncloud
.android
.services
.OperationsService
;
82 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
83 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
86 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
87 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
88 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
89 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
92 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
93 import com
.owncloud
.android
.utils
.DisplayUtils
;
94 import com
.owncloud
.android
.utils
.Log_OC
;
98 * Displays, what files the user has available in his ownCloud.
100 * @author Bartek Przybylski
101 * @author David A. Velasco
104 public class FileDisplayActivity
extends HookActivity
implements
105 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
, EditNameDialogListener
{
107 private ArrayAdapter
<String
> mDirectories
;
109 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
110 private UploadFinishReceiver mUploadFinishReceiver
;
111 private DownloadFinishReceiver mDownloadFinishReceiver
;
112 //private OperationsServiceReceiver mOperationsServiceReceiver;
113 private FileDownloaderBinder mDownloaderBinder
= null
;
114 private FileUploaderBinder mUploaderBinder
= null
;
115 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
116 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
118 private boolean mDualPane
;
119 private View mLeftFragmentContainer
;
120 private View mRightFragmentContainer
;
122 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
123 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
124 //private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
125 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
127 public static final int DIALOG_SHORT_WAIT
= 0;
128 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
129 //private static final int DIALOG_SSL_VALIDATOR = 2;
130 private static final int DIALOG_CERT_NOT_SAVED
= 2;
132 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
134 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
135 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
137 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
139 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
140 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
142 private OCFile mWaitingToPreview
;
144 private boolean mSyncInProgress
= false
;
145 //private boolean mRefreshSharesInProgress = false;
147 private String DIALOG_UNTRUSTED_CERT
;
149 private OCFile mWaitingToSend
;
152 protected void onCreate(Bundle savedInstanceState
) {
153 Log_OC
.d(TAG
, "onCreate() start");
154 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
156 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
158 /// bindings to transference services
159 mUploadConnection
= new ListServiceConnection();
160 mDownloadConnection
= new ListServiceConnection();
161 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
162 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
164 // PIN CODE request ; best location is to decide, let's try this first
165 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
167 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
172 Intent observer_intent
= new Intent(this, FileObserverService
.class);
173 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
174 startService(observer_intent
);
176 /// Load of saved instance state
177 if(savedInstanceState
!= null
) {
178 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
179 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
180 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
181 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
184 mWaitingToPreview
= null
;
185 mSyncInProgress
= false
;
186 //mRefreshSharesInProgress = false;
187 mWaitingToSend
= null
;
192 // Inflate and set the layout view
193 setContentView(R
.layout
.files
);
194 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
195 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
196 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
197 if (savedInstanceState
== null
) {
198 createMinFragments();
200 Log_OC
.d(TAG
, "Init the secondFragment again");
202 initFragmentsWithFile();
207 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
208 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
209 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
211 Log_OC
.d(TAG
, "onCreate() end");
215 protected void onStart() {
217 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
219 refeshListOfFilesFragment();
224 protected void onDestroy() {
226 if (mDownloadConnection
!= null
)
227 unbindService(mDownloadConnection
);
228 if (mUploadConnection
!= null
)
229 unbindService(mUploadConnection
);
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
);
422 protected void refeshListOfFilesFragment() {
423 OCFileListFragment fileListFragment = getListOfFilesFragment();
424 if (fileListFragment != null) {
425 fileListFragment.listDirectory();
430 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
431 FileFragment secondFragment
= getSecondFragment();
432 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
433 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
434 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
435 OCFile fileInFragment
= detailsFragment
.getFile();
436 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
437 // the user browsed to other file ; forget the automatic preview
438 mWaitingToPreview
= null
;
440 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
441 // grant that the right panel updates the progress bar
442 detailsFragment
.listenForTransferProgress();
443 detailsFragment
.updateFileDetails(true
, false
);
445 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
446 // update the right panel
447 boolean detailsFragmentChanged
= false
;
450 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
451 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
452 startMediaPreview(mWaitingToPreview
, 0, true
);
453 detailsFragmentChanged
= true
;
455 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
458 mWaitingToPreview
= null
;
460 if (!detailsFragmentChanged
) {
461 detailsFragment
.updateFileDetails(false
, (success
));
468 public boolean onCreateOptionsMenu(Menu menu
) {
469 MenuInflater inflater
= getSherlock().getMenuInflater();
470 inflater
.inflate(R
.menu
.main_menu
, menu
);
475 public boolean onOptionsItemSelected(MenuItem item
) {
476 boolean retval
= true
;
477 switch (item
.getItemId()) {
478 case R
.id
.action_create_dir
: {
479 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
480 dialog
.show(getSupportFragmentManager(), "createdirdialog");
483 case R
.id
.action_sync_account
: {
484 startSynchronization();
487 case R
.id
.action_upload
: {
488 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
491 case R
.id
.action_settings
: {
492 Intent settingsIntent
= new Intent(this, Preferences
.class);
493 startActivity(settingsIntent
);
496 case android
.R
.id
.home
: {
497 FileFragment second
= getSecondFragment();
498 OCFile currentDir
= getCurrentDir();
499 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
500 (second
!= null
&& second
.getFile() != null
)) {
507 retval
= super.onOptionsItemSelected(item
);
512 private void startSynchronization() {
513 Log_OC
.e(TAG
, "Got to start sync");
514 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
515 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
516 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
517 Bundle bundle
= new Bundle();
518 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
519 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
520 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
521 ContentResolver
.requestSync(
523 MainApp
.getAuthority(), bundle
);
525 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
526 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
527 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
528 builder
.setExpedited(true
);
529 builder
.setManual(true
);
531 SyncRequest request
= builder
.build();
532 ContentResolver
.requestSync(request
);
538 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
539 if (itemPosition
!= 0) {
540 String targetPath
= "";
541 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
542 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
544 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
545 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
546 if (targetFolder
!= null
) {
547 browseTo(targetFolder
);
550 // the next operation triggers a new call to this method, but it's necessary to
551 // ensure that the name exposed in the action bar is the current directory when the
552 // user selected it in the navigation list
553 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
554 getSupportActionBar().setSelectedNavigationItem(0);
560 * Called, when the user selected something for uploading
562 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
563 super.onActivityResult(requestCode
, resultCode
, data
);
565 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
566 requestSimpleUpload(data
, resultCode
);
568 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
569 requestMultipleUpload(data
, resultCode
);
574 private void requestMultipleUpload(Intent data
, int resultCode
) {
575 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
576 if (filePaths
!= null
) {
577 String
[] remotePaths
= new String
[filePaths
.length
];
578 String remotePathBase
= "";
579 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
580 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
582 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
583 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
584 for (int j
= 0; j
< remotePaths
.length
; j
++) {
585 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
588 Intent i
= new Intent(this, FileUploader
.class);
589 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
590 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
591 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
592 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
593 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
594 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
598 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
599 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
606 private void requestSimpleUpload(Intent data
, int resultCode
) {
607 String filepath
= null
;
609 Uri selectedImageUri
= data
.getData();
611 String filemanagerstring
= selectedImageUri
.getPath();
612 String selectedImagePath
= getPath(selectedImageUri
);
614 if (selectedImagePath
!= null
)
615 filepath
= selectedImagePath
;
617 filepath
= filemanagerstring
;
619 } catch (Exception e
) {
620 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
624 if (filepath
== null
) {
625 Log_OC
.e(TAG
, "Couldnt resolve path to file");
626 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
632 Intent i
= new Intent(this, FileUploader
.class);
633 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
635 String remotepath
= new String();
636 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
637 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
639 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
640 remotepath
+= OCFile
.PATH_SEPARATOR
;
641 remotepath
+= new File(filepath
).getName();
643 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
644 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
645 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
646 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
647 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
652 public void onBackPressed() {
653 OCFileListFragment listOfFiles
= getListOfFilesFragment();
654 if (mDualPane
|| getSecondFragment() == null
) {
655 if (listOfFiles
!= null
) { // should never be null, indeed
656 if (mDirectories
.getCount() <= 1) {
660 int levelsUp
= listOfFiles
.onBrowseUp();
661 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
666 if (listOfFiles
!= null
) { // should never be null, indeed
667 setFile(listOfFiles
.getCurrentFile());
669 cleanSecondFragment();
674 protected void onSaveInstanceState(Bundle outState
) {
675 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
676 Log_OC
.e(TAG
, "onSaveInstanceState() start");
677 super.onSaveInstanceState(outState
);
678 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
679 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
680 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
681 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
683 Log_OC
.d(TAG
, "onSaveInstanceState() end");
689 protected void onResume() {
691 Log_OC
.e(TAG
, "onResume() start");
693 // Listen for sync messages
694 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
695 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
696 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
697 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
698 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
699 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
700 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
701 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
702 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
704 // Listen for upload messages
705 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
706 mUploadFinishReceiver
= new UploadFinishReceiver();
707 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
709 // Listen for download messages
710 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
711 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
712 mDownloadFinishReceiver
= new DownloadFinishReceiver();
713 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
715 // Listen for messages from the OperationsService
717 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
718 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
719 mOperationsServiceReceiver = new OperationsServiceReceiver();
720 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
723 Log_OC
.d(TAG
, "onResume() end");
728 protected void onPause() {
730 Log_OC
.e(TAG
, "onPause() start");
731 if (mSyncBroadcastReceiver
!= null
) {
732 unregisterReceiver(mSyncBroadcastReceiver
);
733 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
734 mSyncBroadcastReceiver
= null
;
736 if (mUploadFinishReceiver
!= null
) {
737 unregisterReceiver(mUploadFinishReceiver
);
738 mUploadFinishReceiver
= null
;
740 if (mDownloadFinishReceiver
!= null
) {
741 unregisterReceiver(mDownloadFinishReceiver
);
742 mDownloadFinishReceiver
= null
;
745 if (mOperationsServiceReceiver != null) {
746 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
747 mOperationsServiceReceiver = null;
750 Log_OC
.d(TAG
, "onPause() end");
755 protected Dialog
onCreateDialog(int id
) {
756 Dialog dialog
= null
;
757 AlertDialog
.Builder builder
;
759 case DIALOG_SHORT_WAIT
: {
760 ProgressDialog working_dialog
= new ProgressDialog(this);
761 working_dialog
.setMessage(getResources().getString(
762 R
.string
.wait_a_moment
));
763 working_dialog
.setIndeterminate(true
);
764 working_dialog
.setCancelable(false
);
765 dialog
= working_dialog
;
768 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
770 String
[] items
= null
;
772 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
773 getString(R
.string
.actionbar_upload_from_apps
),
774 getString(R
.string
.actionbar_failed_instant_upload
) };
776 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
777 getString(R
.string
.actionbar_upload_from_apps
) };
779 if (InstantUploadActivity
.IS_ENABLED
)
784 builder
= new AlertDialog
.Builder(this);
785 builder
.setTitle(R
.string
.actionbar_upload
);
786 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
787 public void onClick(DialogInterface dialog
, int item
) {
790 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
791 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
792 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
794 // TODO create and handle new fragment
795 // LocalFileListFragment
797 } else if (item
== 1) {
798 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
799 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
800 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
801 ACTION_SELECT_CONTENT_FROM_APPS
);
802 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
803 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
804 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
805 startActivity(action
);
809 dialog
= builder
.create();
812 case DIALOG_CERT_NOT_SAVED
: {
813 builder
= new AlertDialog
.Builder(this);
814 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
815 builder
.setCancelable(false
);
816 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
818 public void onClick(DialogInterface dialog
, int which
) {
822 dialog
= builder
.create();
834 * Translates a content URI of an image to a physical path
836 * @param uri The URI to resolve
837 * @return The path to the image or null if it could not be found
839 public String
getPath(Uri uri
) {
840 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
841 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
842 if (cursor
!= null
) {
843 int column_index
= cursor
844 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
845 cursor
.moveToFirst();
846 return cursor
.getString(column_index
);
852 * Pushes a directory to the drop down list
853 * @param directory to push
854 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
856 public void pushDirname(OCFile directory
) {
857 if(!directory
.isFolder()){
858 throw new IllegalArgumentException("Only directories may be pushed!");
860 mDirectories
.insert(directory
.getFileName(), 0);
865 * Pops a directory name from the drop down list
866 * @return True, unless the stack is empty
868 public boolean popDirname() {
869 mDirectories
.remove(mDirectories
.getItem(0));
870 return !mDirectories
.isEmpty();
873 // Custom array adapter to override text colors
874 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
876 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
880 public View
getView(int position
, View convertView
, ViewGroup parent
) {
881 View v
= super.getView(position
, convertView
, parent
);
883 ((TextView
) v
).setTextColor(getResources().getColorStateList(
884 android
.R
.color
.white
));
886 fixRoot((TextView
) v
);
890 public View
getDropDownView(int position
, View convertView
,
892 View v
= super.getDropDownView(position
, convertView
, parent
);
894 ((TextView
) v
).setTextColor(getResources().getColorStateList(
895 android
.R
.color
.white
));
897 fixRoot((TextView
) v
);
901 private void fixRoot(TextView v
) {
902 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
903 v
.setText(R
.string
.default_display_name_for_root_folder
);
909 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
912 * {@link BroadcastReceiver} to enable syncing feedback in UI
915 public void onReceive(Context context
, Intent intent
) {
917 String event
= intent
.getAction();
918 Log_OC
.d(TAG
, "Received broadcast " + event
);
919 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
920 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
921 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
922 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
926 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
927 mSyncInProgress
= true
;
930 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
931 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
933 if (currentDir
== null
) {
934 // current folder was removed from the server
935 Toast
.makeText( FileDisplayActivity
.this,
936 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
942 if (currentFile
== null
&& !getFile().isFolder()) {
943 // currently selected file was removed in the server, and now we know it
944 cleanSecondFragment();
945 currentFile
= currentDir
;
949 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
950 OCFileListFragment fileListFragment = getListOfFilesFragment();
951 if (fileListFragment != null) {
952 fileListFragment.listDirectory(currentDir);
956 setFile(currentFile
);
959 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
962 if (synchResult != null &&
963 synchResult.isSuccess() &&
964 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
965 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
967 !mRefreshSharesInProgress &&
968 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
975 removeStickyBroadcast(intent
);
976 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
977 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
980 if (synchResult
!= null
) {
981 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
982 mLastSslUntrustedServerResult
= synchResult
;
985 } catch (RuntimeException e
) {
986 // avoid app crashes after changing the serial id of RemoteOperationResult
987 // in owncloud library with broadcast notifications pending to process
988 removeStickyBroadcast(intent
);
994 private class UploadFinishReceiver
extends BroadcastReceiver
{
996 * Once the file upload has finished -> update view
997 * @author David A. Velasco
998 * {@link BroadcastReceiver} to enable upload feedback in UI
1001 public void onReceive(Context context
, Intent intent
) {
1002 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1003 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1004 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1005 OCFile currentDir
= getCurrentDir();
1006 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1007 if (sameAccount
&& isDescendant
) {
1009 refeshListOfFilesFragment();
1018 * Class waiting for broadcast events from the {@link FielDownloader} service.
1020 * Updates the UI when a download is started or finished, provided that it is relevant for the
1023 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1025 public void onReceive(Context context
, Intent intent
) {
1026 boolean sameAccount
= isSameAccount(context
, intent
);
1027 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1028 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1030 if (sameAccount
&& isDescendant
) {
1032 refeshListOfFilesFragment();
1034 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1037 if (mWaitingToSend
!= null
) {
1038 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1039 if (mWaitingToSend
.isDown()) {
1040 sendDownloadedFile();
1044 removeStickyBroadcast(intent
);
1047 private boolean isDescendant(String downloadedRemotePath
) {
1048 OCFile currentDir
= getCurrentDir();
1049 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1052 private boolean isSameAccount(Context context
, Intent intent
) {
1053 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1054 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1060 * Class waiting for broadcast events from the {@link OperationsService}.
1062 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1063 * operation performed in {@link OperationsService}.
1065 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1066 * probably all the operations associated to the app model.
1068 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1071 public void onReceive(Context context
, Intent intent
) {
1072 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1074 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1075 //mRefreshSharesInProgress = false;
1077 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1078 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1079 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1080 && getStorageManager() != null
1083 refeshListOfFilesFragment();
1086 if ((getSharesResult
!= null
) &&
1087 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1088 mLastSslUntrustedServerResult
= getSharesResult
;
1089 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1092 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1099 public void browseToRoot() {
1100 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1101 if (listOfFiles
!= null
) { // should never be null, indeed
1102 while (mDirectories
.getCount() > 1) {
1105 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1106 listOfFiles
.listDirectory(root
);
1107 setFile(listOfFiles
.getCurrentFile());
1108 startSyncFolderOperation(root
);
1110 cleanSecondFragment();
1114 public void browseTo(OCFile folder
) {
1115 if (folder
== null
|| !folder
.isFolder()) {
1116 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1118 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1119 if (listOfFiles
!= null
) {
1120 setNavigationListWithFolder(folder
);
1121 listOfFiles
.listDirectory(folder
);
1122 setFile(listOfFiles
.getCurrentFile());
1123 startSyncFolderOperation(folder
);
1125 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1127 cleanSecondFragment();
1134 * Updates action bar and second fragment, if in dual pane mode.
1137 public void onBrowsedDownTo(OCFile directory
) {
1138 pushDirname(directory
);
1139 cleanSecondFragment();
1142 startSyncFolderOperation(directory
);
1147 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1149 * @param file Image {@link OCFile} to show.
1152 public void startImagePreview(OCFile file
) {
1153 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1154 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1155 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1156 startActivity(showDetailsIntent
);
1160 * Stars the preview of an already down media {@link OCFile}.
1162 * @param file Media {@link OCFile} to preview.
1163 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1164 * @param autoplay When 'true', the playback will start without user interactions.
1167 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1168 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1169 setSecondFragment(mediaFragment
);
1170 updateFragmentsVisibility(true
);
1171 updateNavigationElementsInActionBar(file
);
1176 * Requests the download of the received {@link OCFile} , updates the UI
1177 * to monitor the download progress and prepares the activity to preview
1178 * or open the file when the download finishes.
1180 * @param file {@link OCFile} to download and preview.
1183 public void startDownloadForPreview(OCFile file
) {
1184 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1185 setSecondFragment(detailFragment
);
1186 mWaitingToPreview
= file
;
1187 requestForDownload();
1188 updateFragmentsVisibility(true
);
1189 updateNavigationElementsInActionBar(file
);
1195 * Shows the information of the {@link OCFile} received as a
1196 * parameter in the second fragment.
1198 * @param file {@link OCFile} whose details will be shown
1201 public void showDetails(OCFile file
) {
1202 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1203 setSecondFragment(detailFragment
);
1204 updateFragmentsVisibility(true
);
1205 updateNavigationElementsInActionBar(file
);
1213 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1214 ActionBar actionBar
= getSupportActionBar();
1215 if (chosenFile
== null
|| mDualPane
) {
1216 // only list of files - set for browsing through folders
1217 OCFile currentDir
= getCurrentDir();
1218 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1219 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1220 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1222 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1224 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1225 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1228 actionBar
.setDisplayHomeAsUpEnabled(true
);
1229 actionBar
.setDisplayShowTitleEnabled(true
);
1230 actionBar
.setTitle(chosenFile
.getFileName());
1231 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1241 public void onFileStateChanged() {
1243 refeshListOfFilesFragment();
1244 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1253 public FileDownloaderBinder
getFileDownloaderBinder() {
1254 return mDownloaderBinder
;
1262 public FileUploaderBinder
getFileUploaderBinder() {
1263 return mUploaderBinder
;
1267 /** Defines callbacks for service binding, passed to bindService() */
1268 private class ListServiceConnection
implements ServiceConnection
{
1271 public void onServiceConnected(ComponentName component
, IBinder service
) {
1272 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1273 Log_OC
.d(TAG
, "Download service connected");
1274 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1275 if (mWaitingToPreview
!= null
) {
1276 requestForDownload();
1279 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1280 Log_OC
.d(TAG
, "Upload service connected");
1281 mUploaderBinder
= (FileUploaderBinder
) service
;
1285 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1286 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1287 if (listOfFiles
!= null
) {
1288 listOfFiles
.listDirectory();
1290 FileFragment secondFragment
= getSecondFragment();
1291 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1292 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1293 detailFragment
.listenForTransferProgress();
1294 detailFragment
.updateFileDetails(false
, false
);
1299 public void onServiceDisconnected(ComponentName component
) {
1300 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1301 Log_OC
.d(TAG
, "Download service disconnected");
1302 mDownloaderBinder
= null
;
1303 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1304 Log_OC
.d(TAG
, "Upload service disconnected");
1305 mUploaderBinder
= null
;
1313 * Launch an intent to request the PIN code to the user before letting him use the app
1315 private void requestPinCode() {
1316 boolean pinStart
= false
;
1317 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1318 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1320 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1321 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1328 public void onSavedCertificate() {
1329 startSyncFolderOperation(getCurrentDir());
1334 public void onFailedSavingCertificate() {
1335 showDialog(DIALOG_CERT_NOT_SAVED
);
1339 public void onCancelCertificate() {
1344 * Updates the view associated to the activity after the finish of some operation over files
1345 * in the current account.
1347 * @param operation Removal operation performed.
1348 * @param result Result of the removal.
1351 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1352 super.onRemoteOperationFinish(operation
, result
);
1354 if (operation
instanceof RemoveFileOperation
) {
1355 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1357 } else if (operation
instanceof RenameFileOperation
) {
1358 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1360 } else if (operation
instanceof SynchronizeFileOperation
) {
1361 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1363 } else if (operation
instanceof CreateFolderOperation
) {
1364 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1366 } else if (operation
instanceof CreateShareOperation
) {
1367 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1369 } else if (operation
instanceof UnshareLinkOperation
) {
1370 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1377 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1378 if (result
.isSuccess()) {
1379 refreshShowDetails();
1381 refeshListOfFilesFragment();
1387 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1388 if (result
.isSuccess()) {
1389 refreshShowDetails();
1391 refeshListOfFilesFragment();
1393 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1394 cleanSecondFragment();
1396 refeshListOfFilesFragment();
1401 private void refreshShowDetails() {
1402 FileFragment details
= getSecondFragment();
1403 if (details
!= null
) {
1404 OCFile file
= details
.getFile();
1406 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1407 if (details
instanceof PreviewMediaFragment
) {
1408 // Refresh OCFile of the fragment
1409 ((PreviewMediaFragment
) details
).updateFile(file
);
1414 invalidateOptionsMenu();
1419 * Updates the view associated to the activity after the finish of an operation trying to remove a
1422 * @param operation Removal operation performed.
1423 * @param result Result of the removal.
1425 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1426 dismissLoadingDialog();
1427 if (result
.isSuccess()) {
1428 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1430 OCFile removedFile
= operation
.getFile();
1431 getSecondFragment();
1432 FileFragment second
= getSecondFragment();
1433 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1434 cleanSecondFragment();
1436 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1438 refeshListOfFilesFragment();
1443 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1445 if (result
.isSslRecoverableException()) {
1446 mLastSslUntrustedServerResult
= result
;
1447 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1453 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1455 * @param operation Creation operation performed.
1456 * @param result Result of the creation.
1458 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1459 if (result
.isSuccess()) {
1460 dismissLoadingDialog();
1462 refeshListOfFilesFragment();
1466 dismissLoadingDialog();
1467 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1468 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1471 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1474 } catch (NotFoundException e
) {
1475 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1483 * Updates the view associated to the activity after the finish of an operation trying to rename a
1486 * @param operation Renaming operation performed.
1487 * @param result Result of the renaming.
1489 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1490 dismissLoadingDialog();
1491 OCFile renamedFile
= operation
.getFile();
1492 if (result
.isSuccess()) {
1494 FileFragment details
= getSecondFragment();
1495 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1496 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1499 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1501 refeshListOfFilesFragment();
1506 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1507 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1509 // TODO throw again the new rename dialog
1510 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1511 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1514 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1516 if (result
.isSslRecoverableException()) {
1517 mLastSslUntrustedServerResult
= result
;
1518 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1525 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1526 dismissLoadingDialog();
1527 OCFile syncedFile
= operation
.getLocalFile();
1528 if (!result
.isSuccess()) {
1529 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1530 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1531 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1532 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1538 if (operation
.transferWasRequested()) {
1540 refeshListOfFilesFragment();
1542 onTransferStateChanged(syncedFile
, true
, true
);
1545 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1556 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1558 FileFragment details
= getSecondFragment();
1559 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1560 if (downloading
|| uploading
) {
1561 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1563 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1570 public void onDismiss(EditNameDialog dialog
) {
1571 if (dialog
.getResult()) {
1572 String newDirectoryName
= dialog
.getNewFilename().trim();
1573 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1574 if (newDirectoryName
.length() > 0) {
1575 String path
= getCurrentDir().getRemotePath();
1578 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1579 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1580 operation
.execute( getAccount(),
1581 FileDisplayActivity
.this,
1582 FileDisplayActivity
.this,
1584 FileDisplayActivity
.this);
1586 showLoadingDialog();
1592 private void requestForDownload() {
1593 Account account
= getAccount();
1594 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1595 Intent i
= new Intent(this, FileDownloader
.class);
1596 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1597 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1603 private OCFile
getCurrentDir() {
1604 OCFile file
= getFile();
1606 if (file
.isFolder()) {
1608 } else if (getStorageManager() != null
) {
1609 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1610 return getStorageManager().getFileByPath(parentPath
);
1616 public void startSyncFolderOperation(OCFile folder
) {
1617 long currentSyncTime
= System
.currentTimeMillis();
1619 mSyncInProgress
= true
;
1621 // perform folder synchronization
1622 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1625 getFileOperationsHelper().isSharedSupported(this),
1626 getStorageManager(),
1628 getApplicationContext()
1630 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1632 setSupportProgressBarIndeterminateVisibility(true
);
1636 private void startGetShares() {
1637 // Get shared files/folders
1638 Intent intent = new Intent(this, OperationsService.class);
1639 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1640 startService(intent);
1642 mRefreshSharesInProgress = true;
1647 * Show untrusted cert dialog
1649 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1650 // Show a dialog with the certificate info
1651 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1652 FragmentManager fm
= getSupportFragmentManager();
1653 FragmentTransaction ft
= fm
.beginTransaction();
1654 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1658 * Requests the download of the received {@link OCFile} , updates the UI
1659 * to monitor the download progress and prepares the activity to send the file
1660 * when the download finishes.
1662 * @param file {@link OCFile} to download and preview.
1665 public void startDownloadForSending(OCFile file
) {
1666 mWaitingToSend
= file
;
1667 requestForDownload(mWaitingToSend
);
1668 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1669 updateFragmentsVisibility(hasSecondFragment
);
1672 private void requestForDownload(OCFile file
) {
1673 Account account
= getAccount();
1674 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1675 Intent i
= new Intent(this, FileDownloader
.class);
1676 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1677 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1682 private void sendDownloadedFile(){
1683 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1684 mWaitingToSend
= null
;