1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import android
.accounts
.Account
;
23 import android
.app
.AlertDialog
;
24 import android
.app
.Dialog
;
25 import android
.app
.ProgressDialog
;
26 import android
.content
.BroadcastReceiver
;
27 import android
.content
.ComponentName
;
28 import android
.content
.ContentResolver
;
29 import android
.content
.Context
;
30 import android
.content
.DialogInterface
;
31 import android
.content
.Intent
;
32 import android
.content
.IntentFilter
;
33 import android
.content
.ServiceConnection
;
34 import android
.content
.SharedPreferences
;
35 import android
.content
.SyncRequest
;
36 import android
.content
.res
.Resources
.NotFoundException
;
37 import android
.database
.Cursor
;
38 import android
.net
.Uri
;
39 import android
.os
.Bundle
;
40 import android
.os
.IBinder
;
41 import android
.preference
.PreferenceManager
;
42 import android
.provider
.MediaStore
;
43 import android
.support
.v4
.app
.Fragment
;
44 import android
.support
.v4
.app
.FragmentManager
;
45 import android
.support
.v4
.app
.FragmentTransaction
;
46 //import android.support.v4.content.LocalBroadcastManager;
47 import android
.util
.Log
;
48 import android
.view
.View
;
49 import android
.view
.ViewGroup
;
50 import android
.widget
.ArrayAdapter
;
51 import android
.widget
.TextView
;
52 import android
.widget
.Toast
;
54 import com
.actionbarsherlock
.app
.ActionBar
;
55 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
56 import com
.actionbarsherlock
.view
.Menu
;
57 import com
.actionbarsherlock
.view
.MenuInflater
;
58 import com
.actionbarsherlock
.view
.MenuItem
;
59 import com
.actionbarsherlock
.view
.Window
;
60 import com
.owncloud
.android
.MainApp
;
61 import com
.owncloud
.android
.R
;
62 import com
.owncloud
.android
.datamodel
.OCFile
;
63 import com
.owncloud
.android
.files
.services
.FileDownloader
;
64 import com
.owncloud
.android
.files
.services
.FileObserverService
;
65 import com
.owncloud
.android
.files
.services
.FileUploader
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
68 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
70 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
74 import com
.owncloud
.android
.operations
.CreateShareOperation
;
75 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
76 import com
.owncloud
.android
.operations
.RenameFileOperation
;
77 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
78 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
79 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
80 import com
.owncloud
.android
.services
.OperationsService
;
81 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
82 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
83 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
85 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
86 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
87 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
88 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
89 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
92 import com
.owncloud
.android
.utils
.DisplayUtils
;
93 import com
.owncloud
.android
.utils
.Log_OC
;
97 * Displays, what files the user has available in his ownCloud.
99 * @author Bartek Przybylski
100 * @author David A. Velasco
103 public class FileDisplayActivity
extends HookActivity
implements
104 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
, EditNameDialogListener
{
106 private ArrayAdapter
<String
> mDirectories
;
108 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
109 private UploadFinishReceiver mUploadFinishReceiver
;
110 private DownloadFinishReceiver mDownloadFinishReceiver
;
111 //private OperationsServiceReceiver mOperationsServiceReceiver;
112 private FileDownloaderBinder mDownloaderBinder
= null
;
113 private FileUploaderBinder mUploaderBinder
= null
;
114 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
115 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
117 private boolean mDualPane
;
118 private View mLeftFragmentContainer
;
119 private View mRightFragmentContainer
;
121 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
122 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
123 //private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
124 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
126 public static final int DIALOG_SHORT_WAIT
= 0;
127 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
128 //private static final int DIALOG_SSL_VALIDATOR = 2;
129 private static final int DIALOG_CERT_NOT_SAVED
= 2;
131 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
133 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
134 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
136 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
138 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
139 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
141 private OCFile mWaitingToPreview
;
143 private boolean mSyncInProgress
= false
;
144 //private boolean mRefreshSharesInProgress = false;
146 private String DIALOG_UNTRUSTED_CERT
;
148 private OCFile mWaitingToSend
;
151 protected void onCreate(Bundle savedInstanceState
) {
152 Log_OC
.d(TAG
, "onCreate() start");
153 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
155 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
157 /// bindings to transference services
158 mUploadConnection
= new ListServiceConnection();
159 mDownloadConnection
= new ListServiceConnection();
160 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
161 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
163 // PIN CODE request ; best location is to decide, let's try this first
164 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
166 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
171 Intent observer_intent
= new Intent(this, FileObserverService
.class);
172 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
173 startService(observer_intent
);
175 /// Load of saved instance state
176 if(savedInstanceState
!= null
) {
177 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
178 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
179 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
180 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
183 mWaitingToPreview
= null
;
184 mSyncInProgress
= false
;
185 //mRefreshSharesInProgress = false;
186 mWaitingToSend
= null
;
191 // Inflate and set the layout view
192 setContentView(R
.layout
.files
);
193 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
194 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
195 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
196 if (savedInstanceState
== null
) {
197 createMinFragments();
199 Log_OC
.d(TAG
, "Init the secondFragment again");
201 initFragmentsWithFile();
206 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
207 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
208 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
210 Log_OC
.d(TAG
, "onCreate() end");
214 protected void onStart() {
216 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
217 refeshListOfFilesFragment();
221 protected void onDestroy() {
223 if (mDownloadConnection
!= null
)
224 unbindService(mDownloadConnection
);
225 if (mUploadConnection
!= null
)
226 unbindService(mUploadConnection
);
230 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
233 protected void onAccountSet(boolean stateWasRecovered
) {
234 super.onAccountSet(stateWasRecovered
);
235 if (getAccount() != null
) {
236 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
237 OCFile file
= getFile();
238 // get parent from path
239 String parentPath
= "";
241 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
242 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
243 // get parent from path
244 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
245 if (getStorageManager().getFileByPath(parentPath
) == null
)
246 file
= null
; // not able to know the directory where the file is uploading
248 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
252 // fall back to root folder
253 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
256 setNavigationListWithFolder(file
);
258 if (!stateWasRecovered
) {
259 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
260 initFragmentsWithFile();
261 if (file
.isFolder()) {
262 startSyncFolderOperation(file
);
266 updateFragmentsVisibility(!file
.isFolder());
267 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
273 private void setNavigationListWithFolder(OCFile file
) {
274 mDirectories
.clear();
275 OCFile fileIt
= file
;
277 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
278 if (fileIt
.isFolder()) {
279 mDirectories
.add(fileIt
.getFileName());
281 // get parent from path
282 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
283 fileIt
= getStorageManager().getFileByPath(parentPath
);
285 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
289 private void createMinFragments() {
290 OCFileListFragment listOfFiles
= new OCFileListFragment();
291 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
292 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
293 transaction
.commit();
296 private void initFragmentsWithFile() {
297 if (getAccount() != null
&& getFile() != null
) {
299 OCFileListFragment listOfFiles
= getListOfFilesFragment();
300 if (listOfFiles
!= null
) {
301 listOfFiles
.listDirectory(getCurrentDir());
303 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
307 OCFile file
= getFile();
308 Fragment secondFragment
= chooseInitialSecondFragment(file
);
309 if (secondFragment
!= null
) {
310 setSecondFragment(secondFragment
);
311 updateFragmentsVisibility(true
);
312 updateNavigationElementsInActionBar(file
);
315 cleanSecondFragment();
319 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
320 if (getAccount() == null
) {
321 Log
.wtf(TAG
, "\t account is NULL");
323 if (getFile() == null
) {
324 Log
.wtf(TAG
, "\t file is NULL");
329 private Fragment
chooseInitialSecondFragment(OCFile file
) {
330 Fragment secondFragment
= null
;
331 if (file
!= null
&& !file
.isFolder()) {
332 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
333 && file
.getLastSyncDateForProperties() > 0 // temporal fix
335 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
336 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
337 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
340 secondFragment
= new FileDetailFragment(file
, getAccount());
343 return secondFragment
;
348 * Replaces the second fragment managed by the activity with the received as
351 * Assumes never will be more than two fragments managed at the same time.
353 * @param fragment New second Fragment to set.
355 private void setSecondFragment(Fragment fragment
) {
356 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
357 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
358 transaction
.commit();
362 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
364 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
371 } else if (existsSecondFragment
) {
372 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
373 mLeftFragmentContainer
.setVisibility(View
.GONE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
380 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
381 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
383 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
384 mRightFragmentContainer
.setVisibility(View
.GONE
);
390 private OCFileListFragment
getListOfFilesFragment() {
391 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
392 if (listOfFiles
!= null
) {
393 return (OCFileListFragment
)listOfFiles
;
395 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
399 protected FileFragment
getSecondFragment() {
400 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
401 if (second
!= null
) {
402 return (FileFragment
)second
;
407 public void cleanSecondFragment() {
408 Fragment second
= getSecondFragment();
409 if (second
!= null
) {
410 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
414 updateFragmentsVisibility(false
);
415 updateNavigationElementsInActionBar(null
);
418 protected void refeshListOfFilesFragment() {
419 OCFileListFragment fileListFragment
= getListOfFilesFragment();
420 if (fileListFragment
!= null
) {
421 fileListFragment
.listDirectory();
425 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
426 FileFragment secondFragment
= getSecondFragment();
427 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
428 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
429 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
430 OCFile fileInFragment
= detailsFragment
.getFile();
431 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
432 // the user browsed to other file ; forget the automatic preview
433 mWaitingToPreview
= null
;
435 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
436 // grant that the right panel updates the progress bar
437 detailsFragment
.listenForTransferProgress();
438 detailsFragment
.updateFileDetails(true
, false
);
440 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
441 // update the right panel
442 boolean detailsFragmentChanged
= false
;
445 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
446 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
447 startMediaPreview(mWaitingToPreview
, 0, true
);
448 detailsFragmentChanged
= true
;
450 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
453 mWaitingToPreview
= null
;
455 if (!detailsFragmentChanged
) {
456 detailsFragment
.updateFileDetails(false
, (success
));
463 public boolean onCreateOptionsMenu(Menu menu
) {
464 MenuInflater inflater
= getSherlock().getMenuInflater();
465 inflater
.inflate(R
.menu
.main_menu
, menu
);
470 public boolean onOptionsItemSelected(MenuItem item
) {
471 boolean retval
= true
;
472 switch (item
.getItemId()) {
473 case R
.id
.action_create_dir
: {
474 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
475 dialog
.show(getSupportFragmentManager(), "createdirdialog");
478 case R
.id
.action_sync_account
: {
479 startSynchronization();
482 case R
.id
.action_upload
: {
483 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
486 case R
.id
.action_settings
: {
487 Intent settingsIntent
= new Intent(this, Preferences
.class);
488 startActivity(settingsIntent
);
491 case android
.R
.id
.home
: {
492 FileFragment second
= getSecondFragment();
493 OCFile currentDir
= getCurrentDir();
494 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
495 (second
!= null
&& second
.getFile() != null
)) {
502 retval
= super.onOptionsItemSelected(item
);
507 private void startSynchronization() {
508 Log_OC
.e(TAG
, "Got to start sync");
509 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
510 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
511 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
512 Bundle bundle
= new Bundle();
513 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
514 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
515 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
516 ContentResolver
.requestSync(
518 MainApp
.getAuthority(), bundle
);
520 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
521 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
522 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
523 builder
.setExpedited(true
);
524 builder
.setManual(true
);
526 SyncRequest request
= builder
.build();
527 ContentResolver
.requestSync(request
);
533 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
534 if (itemPosition
!= 0) {
535 String targetPath
= "";
536 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
537 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
539 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
540 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
541 if (targetFolder
!= null
) {
542 browseTo(targetFolder
);
545 // the next operation triggers a new call to this method, but it's necessary to
546 // ensure that the name exposed in the action bar is the current directory when the
547 // user selected it in the navigation list
548 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
549 getSupportActionBar().setSelectedNavigationItem(0);
555 * Called, when the user selected something for uploading
557 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
558 super.onActivityResult(requestCode
, resultCode
, data
);
560 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
561 requestSimpleUpload(data
, resultCode
);
563 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
564 requestMultipleUpload(data
, resultCode
);
569 private void requestMultipleUpload(Intent data
, int resultCode
) {
570 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
571 if (filePaths
!= null
) {
572 String
[] remotePaths
= new String
[filePaths
.length
];
573 String remotePathBase
= "";
574 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
575 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
577 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
578 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
579 for (int j
= 0; j
< remotePaths
.length
; j
++) {
580 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
583 Intent i
= new Intent(this, FileUploader
.class);
584 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
585 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
586 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
587 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
588 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
589 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
593 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
594 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
601 private void requestSimpleUpload(Intent data
, int resultCode
) {
602 String filepath
= null
;
604 Uri selectedImageUri
= data
.getData();
606 String filemanagerstring
= selectedImageUri
.getPath();
607 String selectedImagePath
= getPath(selectedImageUri
);
609 if (selectedImagePath
!= null
)
610 filepath
= selectedImagePath
;
612 filepath
= filemanagerstring
;
614 } catch (Exception e
) {
615 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
619 if (filepath
== null
) {
620 Log_OC
.e(TAG
, "Couldnt resolve path to file");
621 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
627 Intent i
= new Intent(this, FileUploader
.class);
628 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
630 String remotepath
= new String();
631 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
632 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
634 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
635 remotepath
+= OCFile
.PATH_SEPARATOR
;
636 remotepath
+= new File(filepath
).getName();
638 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
639 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
640 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
641 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
642 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
647 public void onBackPressed() {
648 OCFileListFragment listOfFiles
= getListOfFilesFragment();
649 if (mDualPane
|| getSecondFragment() == null
) {
650 if (listOfFiles
!= null
) { // should never be null, indeed
651 if (mDirectories
.getCount() <= 1) {
655 int levelsUp
= listOfFiles
.onBrowseUp();
656 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
661 if (listOfFiles
!= null
) { // should never be null, indeed
662 setFile(listOfFiles
.getCurrentFile());
664 cleanSecondFragment();
669 protected void onSaveInstanceState(Bundle outState
) {
670 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
671 Log_OC
.e(TAG
, "onSaveInstanceState() start");
672 super.onSaveInstanceState(outState
);
673 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
674 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
675 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
676 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
678 Log_OC
.d(TAG
, "onSaveInstanceState() end");
684 protected void onResume() {
686 Log_OC
.e(TAG
, "onResume() start");
688 // Listen for sync messages
689 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
690 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
691 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
692 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
693 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
694 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
695 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
696 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
697 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
699 // Listen for upload messages
700 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
701 mUploadFinishReceiver
= new UploadFinishReceiver();
702 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
704 // Listen for download messages
705 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
706 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
707 mDownloadFinishReceiver
= new DownloadFinishReceiver();
708 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
710 // Listen for messages from the OperationsService
712 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
713 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
714 mOperationsServiceReceiver = new OperationsServiceReceiver();
715 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
718 Log_OC
.d(TAG
, "onResume() end");
723 protected void onPause() {
725 Log_OC
.e(TAG
, "onPause() start");
726 if (mSyncBroadcastReceiver
!= null
) {
727 unregisterReceiver(mSyncBroadcastReceiver
);
728 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
729 mSyncBroadcastReceiver
= null
;
731 if (mUploadFinishReceiver
!= null
) {
732 unregisterReceiver(mUploadFinishReceiver
);
733 mUploadFinishReceiver
= null
;
735 if (mDownloadFinishReceiver
!= null
) {
736 unregisterReceiver(mDownloadFinishReceiver
);
737 mDownloadFinishReceiver
= null
;
740 if (mOperationsServiceReceiver != null) {
741 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
742 mOperationsServiceReceiver = null;
745 Log_OC
.d(TAG
, "onPause() end");
750 protected Dialog
onCreateDialog(int id
) {
751 Dialog dialog
= null
;
752 AlertDialog
.Builder builder
;
754 case DIALOG_SHORT_WAIT
: {
755 ProgressDialog working_dialog
= new ProgressDialog(this);
756 working_dialog
.setMessage(getResources().getString(
757 R
.string
.wait_a_moment
));
758 working_dialog
.setIndeterminate(true
);
759 working_dialog
.setCancelable(false
);
760 dialog
= working_dialog
;
763 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
765 String
[] items
= null
;
767 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
768 getString(R
.string
.actionbar_upload_from_apps
),
769 getString(R
.string
.actionbar_failed_instant_upload
) };
771 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
772 getString(R
.string
.actionbar_upload_from_apps
) };
774 if (InstantUploadActivity
.IS_ENABLED
)
779 builder
= new AlertDialog
.Builder(this);
780 builder
.setTitle(R
.string
.actionbar_upload
);
781 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
782 public void onClick(DialogInterface dialog
, int item
) {
785 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
786 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
787 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
789 // TODO create and handle new fragment
790 // LocalFileListFragment
792 } else if (item
== 1) {
793 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
794 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
795 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
796 ACTION_SELECT_CONTENT_FROM_APPS
);
797 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
798 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
799 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
800 startActivity(action
);
804 dialog
= builder
.create();
807 case DIALOG_CERT_NOT_SAVED
: {
808 builder
= new AlertDialog
.Builder(this);
809 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
810 builder
.setCancelable(false
);
811 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
813 public void onClick(DialogInterface dialog
, int which
) {
817 dialog
= builder
.create();
829 * Translates a content URI of an image to a physical path
831 * @param uri The URI to resolve
832 * @return The path to the image or null if it could not be found
834 public String
getPath(Uri uri
) {
835 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
836 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
837 if (cursor
!= null
) {
838 int column_index
= cursor
839 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
840 cursor
.moveToFirst();
841 return cursor
.getString(column_index
);
847 * Pushes a directory to the drop down list
848 * @param directory to push
849 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
851 public void pushDirname(OCFile directory
) {
852 if(!directory
.isFolder()){
853 throw new IllegalArgumentException("Only directories may be pushed!");
855 mDirectories
.insert(directory
.getFileName(), 0);
860 * Pops a directory name from the drop down list
861 * @return True, unless the stack is empty
863 public boolean popDirname() {
864 mDirectories
.remove(mDirectories
.getItem(0));
865 return !mDirectories
.isEmpty();
868 // Custom array adapter to override text colors
869 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
871 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
875 public View
getView(int position
, View convertView
, ViewGroup parent
) {
876 View v
= super.getView(position
, convertView
, parent
);
878 ((TextView
) v
).setTextColor(getResources().getColorStateList(
879 android
.R
.color
.white
));
881 fixRoot((TextView
) v
);
885 public View
getDropDownView(int position
, View convertView
,
887 View v
= super.getDropDownView(position
, convertView
, parent
);
889 ((TextView
) v
).setTextColor(getResources().getColorStateList(
890 android
.R
.color
.white
));
892 fixRoot((TextView
) v
);
896 private void fixRoot(TextView v
) {
897 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
898 v
.setText(R
.string
.default_display_name_for_root_folder
);
904 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
907 * {@link BroadcastReceiver} to enable syncing feedback in UI
910 public void onReceive(Context context
, Intent intent
) {
912 String event
= intent
.getAction();
913 Log_OC
.d(TAG
, "Received broadcast " + event
);
914 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
915 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
916 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
917 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
921 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
922 mSyncInProgress
= true
;
925 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
926 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
928 if (currentDir
== null
) {
929 // current folder was removed from the server
930 Toast
.makeText( FileDisplayActivity
.this,
931 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
937 if (currentFile
== null
&& !getFile().isFolder()) {
938 // currently selected file was removed in the server, and now we know it
939 cleanSecondFragment();
940 currentFile
= currentDir
;
943 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
944 OCFileListFragment fileListFragment
= getListOfFilesFragment();
945 if (fileListFragment
!= null
) {
946 fileListFragment
.listDirectory(currentDir
);
949 setFile(currentFile
);
952 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
955 if (synchResult != null &&
956 synchResult.isSuccess() &&
957 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
958 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
960 !mRefreshSharesInProgress &&
961 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
968 removeStickyBroadcast(intent
);
969 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
970 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
973 if (synchResult
!= null
) {
974 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
975 mLastSslUntrustedServerResult
= synchResult
;
978 } catch (RuntimeException e
) {
979 // avoid app crashes after changing the serial id of RemoteOperationResult
980 // in owncloud library with broadcast notifications pending to process
981 removeStickyBroadcast(intent
);
987 private class UploadFinishReceiver
extends BroadcastReceiver
{
989 * Once the file upload has finished -> update view
990 * @author David A. Velasco
991 * {@link BroadcastReceiver} to enable upload feedback in UI
994 public void onReceive(Context context
, Intent intent
) {
995 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
996 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
997 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
998 OCFile currentDir
= getCurrentDir();
999 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1000 if (sameAccount
&& isDescendant
) {
1001 refeshListOfFilesFragment();
1009 * Class waiting for broadcast events from the {@link FielDownloader} service.
1011 * Updates the UI when a download is started or finished, provided that it is relevant for the
1014 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1016 public void onReceive(Context context
, Intent intent
) {
1017 boolean sameAccount
= isSameAccount(context
, intent
);
1018 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1019 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1021 if (sameAccount
&& isDescendant
) {
1022 refeshListOfFilesFragment();
1023 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1026 if (mWaitingToSend
!= null
) {
1027 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1028 if (mWaitingToSend
.isDown()) {
1029 sendDownloadedFile();
1033 removeStickyBroadcast(intent
);
1036 private boolean isDescendant(String downloadedRemotePath
) {
1037 OCFile currentDir
= getCurrentDir();
1038 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1041 private boolean isSameAccount(Context context
, Intent intent
) {
1042 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1043 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1049 * Class waiting for broadcast events from the {@link OperationsService}.
1051 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1052 * operation performed in {@link OperationsService}.
1054 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1055 * probably all the operations associated to the app model.
1057 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1060 public void onReceive(Context context
, Intent intent
) {
1061 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1063 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1064 //mRefreshSharesInProgress = false;
1066 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1067 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1068 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1069 && getStorageManager() != null
1071 refeshListOfFilesFragment();
1073 if ((getSharesResult
!= null
) &&
1074 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1075 mLastSslUntrustedServerResult
= getSharesResult
;
1076 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1079 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1086 public void browseToRoot() {
1087 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1088 if (listOfFiles
!= null
) { // should never be null, indeed
1089 while (mDirectories
.getCount() > 1) {
1092 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1093 listOfFiles
.listDirectory(root
);
1094 setFile(listOfFiles
.getCurrentFile());
1095 startSyncFolderOperation(root
);
1097 cleanSecondFragment();
1101 public void browseTo(OCFile folder
) {
1102 if (folder
== null
|| !folder
.isFolder()) {
1103 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1105 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1106 if (listOfFiles
!= null
) {
1107 setNavigationListWithFolder(folder
);
1108 listOfFiles
.listDirectory(folder
);
1109 setFile(listOfFiles
.getCurrentFile());
1110 startSyncFolderOperation(folder
);
1112 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1114 cleanSecondFragment();
1121 * Updates action bar and second fragment, if in dual pane mode.
1124 public void onBrowsedDownTo(OCFile directory
) {
1125 pushDirname(directory
);
1126 cleanSecondFragment();
1129 startSyncFolderOperation(directory
);
1134 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1136 * @param file Image {@link OCFile} to show.
1139 public void startImagePreview(OCFile file
) {
1140 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1141 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1142 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1143 startActivity(showDetailsIntent
);
1147 * Stars the preview of an already down media {@link OCFile}.
1149 * @param file Media {@link OCFile} to preview.
1150 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1151 * @param autoplay When 'true', the playback will start without user interactions.
1154 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1155 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1156 setSecondFragment(mediaFragment
);
1157 updateFragmentsVisibility(true
);
1158 updateNavigationElementsInActionBar(file
);
1163 * Requests the download of the received {@link OCFile} , updates the UI
1164 * to monitor the download progress and prepares the activity to preview
1165 * or open the file when the download finishes.
1167 * @param file {@link OCFile} to download and preview.
1170 public void startDownloadForPreview(OCFile file
) {
1171 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1172 setSecondFragment(detailFragment
);
1173 mWaitingToPreview
= file
;
1174 requestForDownload();
1175 updateFragmentsVisibility(true
);
1176 updateNavigationElementsInActionBar(file
);
1182 * Shows the information of the {@link OCFile} received as a
1183 * parameter in the second fragment.
1185 * @param file {@link OCFile} whose details will be shown
1188 public void showDetails(OCFile file
) {
1189 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1190 setSecondFragment(detailFragment
);
1191 updateFragmentsVisibility(true
);
1192 updateNavigationElementsInActionBar(file
);
1200 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1201 ActionBar actionBar
= getSupportActionBar();
1202 if (chosenFile
== null
|| mDualPane
) {
1203 // only list of files - set for browsing through folders
1204 OCFile currentDir
= getCurrentDir();
1205 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1206 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1207 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1209 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1211 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1212 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1215 actionBar
.setDisplayHomeAsUpEnabled(true
);
1216 actionBar
.setDisplayShowTitleEnabled(true
);
1217 actionBar
.setTitle(chosenFile
.getFileName());
1218 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1227 public void onFileStateChanged() {
1228 refeshListOfFilesFragment();
1229 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1237 public FileDownloaderBinder
getFileDownloaderBinder() {
1238 return mDownloaderBinder
;
1246 public FileUploaderBinder
getFileUploaderBinder() {
1247 return mUploaderBinder
;
1251 /** Defines callbacks for service binding, passed to bindService() */
1252 private class ListServiceConnection
implements ServiceConnection
{
1255 public void onServiceConnected(ComponentName component
, IBinder service
) {
1256 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1257 Log_OC
.d(TAG
, "Download service connected");
1258 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1259 if (mWaitingToPreview
!= null
) {
1260 requestForDownload();
1263 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1264 Log_OC
.d(TAG
, "Upload service connected");
1265 mUploaderBinder
= (FileUploaderBinder
) service
;
1269 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1270 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1271 if (listOfFiles
!= null
) {
1272 listOfFiles
.listDirectory();
1274 FileFragment secondFragment
= getSecondFragment();
1275 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1276 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1277 detailFragment
.listenForTransferProgress();
1278 detailFragment
.updateFileDetails(false
, false
);
1283 public void onServiceDisconnected(ComponentName component
) {
1284 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1285 Log_OC
.d(TAG
, "Download service disconnected");
1286 mDownloaderBinder
= null
;
1287 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1288 Log_OC
.d(TAG
, "Upload service disconnected");
1289 mUploaderBinder
= null
;
1297 * Launch an intent to request the PIN code to the user before letting him use the app
1299 private void requestPinCode() {
1300 boolean pinStart
= false
;
1301 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1302 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1304 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1305 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1312 public void onSavedCertificate() {
1313 startSyncFolderOperation(getCurrentDir());
1318 public void onFailedSavingCertificate() {
1319 showDialog(DIALOG_CERT_NOT_SAVED
);
1323 public void onCancelCertificate() {
1328 * Updates the view associated to the activity after the finish of some operation over files
1329 * in the current account.
1331 * @param operation Removal operation performed.
1332 * @param result Result of the removal.
1335 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1336 super.onRemoteOperationFinish(operation
, result
);
1338 if (operation
instanceof RemoveFileOperation
) {
1339 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1341 } else if (operation
instanceof RenameFileOperation
) {
1342 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1344 } else if (operation
instanceof SynchronizeFileOperation
) {
1345 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1347 } else if (operation
instanceof CreateFolderOperation
) {
1348 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1350 } else if (operation
instanceof CreateShareOperation
) {
1351 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1353 } else if (operation
instanceof UnshareLinkOperation
) {
1354 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1361 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1362 if (result
.isSuccess()) {
1363 refreshShowDetails();
1364 refeshListOfFilesFragment();
1369 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1370 if (result
.isSuccess()) {
1371 refreshShowDetails();
1372 refeshListOfFilesFragment();
1373 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1374 cleanSecondFragment();
1375 refeshListOfFilesFragment();
1379 private void refreshShowDetails() {
1380 FileFragment details
= getSecondFragment();
1381 if (details
!= null
) {
1382 OCFile file
= details
.getFile();
1384 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1385 if (details
instanceof PreviewMediaFragment
) {
1386 // Refresh OCFile of the fragment
1387 ((PreviewMediaFragment
) details
).updateFile(file
);
1392 invalidateOptionsMenu();
1397 * Updates the view associated to the activity after the finish of an operation trying to remove a
1400 * @param operation Removal operation performed.
1401 * @param result Result of the removal.
1403 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1404 dismissLoadingDialog();
1405 if (result
.isSuccess()) {
1406 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1408 OCFile removedFile
= operation
.getFile();
1409 getSecondFragment();
1410 FileFragment second
= getSecondFragment();
1411 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1412 cleanSecondFragment();
1414 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1415 refeshListOfFilesFragment();
1419 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1421 if (result
.isSslRecoverableException()) {
1422 mLastSslUntrustedServerResult
= result
;
1423 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1429 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1431 * @param operation Creation operation performed.
1432 * @param result Result of the creation.
1434 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1435 if (result
.isSuccess()) {
1436 dismissLoadingDialog();
1437 refeshListOfFilesFragment();
1440 dismissLoadingDialog();
1441 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1442 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1445 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1448 } catch (NotFoundException e
) {
1449 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1457 * Updates the view associated to the activity after the finish of an operation trying to rename a
1460 * @param operation Renaming operation performed.
1461 * @param result Result of the renaming.
1463 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1464 dismissLoadingDialog();
1465 OCFile renamedFile
= operation
.getFile();
1466 if (result
.isSuccess()) {
1468 FileFragment details
= getSecondFragment();
1469 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1470 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1473 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1474 refeshListOfFilesFragment();
1478 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1479 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1481 // TODO throw again the new rename dialog
1482 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1483 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1486 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1488 if (result
.isSslRecoverableException()) {
1489 mLastSslUntrustedServerResult
= result
;
1490 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1497 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1498 dismissLoadingDialog();
1499 OCFile syncedFile
= operation
.getLocalFile();
1500 if (!result
.isSuccess()) {
1501 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1502 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1503 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1504 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1510 if (operation
.transferWasRequested()) {
1511 refeshListOfFilesFragment();
1512 onTransferStateChanged(syncedFile
, true
, true
);
1515 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1526 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1528 FileFragment details
= getSecondFragment();
1529 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1530 if (downloading
|| uploading
) {
1531 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1533 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1540 public void onDismiss(EditNameDialog dialog
) {
1541 if (dialog
.getResult()) {
1542 String newDirectoryName
= dialog
.getNewFilename().trim();
1543 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1544 if (newDirectoryName
.length() > 0) {
1545 String path
= getCurrentDir().getRemotePath();
1548 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1549 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1550 operation
.execute( getAccount(),
1551 FileDisplayActivity
.this,
1552 FileDisplayActivity
.this,
1554 FileDisplayActivity
.this);
1556 showLoadingDialog();
1562 private void requestForDownload() {
1563 Account account
= getAccount();
1564 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1565 Intent i
= new Intent(this, FileDownloader
.class);
1566 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1567 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1573 private OCFile
getCurrentDir() {
1574 OCFile file
= getFile();
1576 if (file
.isFolder()) {
1578 } else if (getStorageManager() != null
) {
1579 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1580 return getStorageManager().getFileByPath(parentPath
);
1586 public void startSyncFolderOperation(OCFile folder
) {
1587 long currentSyncTime
= System
.currentTimeMillis();
1589 mSyncInProgress
= true
;
1591 // perform folder synchronization
1592 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1595 getFileOperationsHelper().isSharedSupported(this),
1596 getStorageManager(),
1598 getApplicationContext()
1600 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1602 setSupportProgressBarIndeterminateVisibility(true
);
1606 private void startGetShares() {
1607 // Get shared files/folders
1608 Intent intent = new Intent(this, OperationsService.class);
1609 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1610 startService(intent);
1612 mRefreshSharesInProgress = true;
1617 * Show untrusted cert dialog
1619 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1620 // Show a dialog with the certificate info
1621 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1622 FragmentManager fm
= getSupportFragmentManager();
1623 FragmentTransaction ft
= fm
.beginTransaction();
1624 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1628 * Requests the download of the received {@link OCFile} , updates the UI
1629 * to monitor the download progress and prepares the activity to send the file
1630 * when the download finishes.
1632 * @param file {@link OCFile} to download and preview.
1635 public void startDownloadForSending(OCFile file
) {
1636 mWaitingToSend
= file
;
1637 requestForDownload(mWaitingToSend
);
1638 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1639 updateFragmentsVisibility(hasSecondFragment
);
1642 private void requestForDownload(OCFile file
) {
1643 Account account
= getAccount();
1644 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1645 Intent i
= new Intent(this, FileDownloader
.class);
1646 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1647 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1652 private void sendDownloadedFile(){
1653 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1654 mWaitingToSend
= null
;