1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 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 java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.util
.Log
;
52 import android
.view
.View
;
53 import android
.view
.ViewGroup
;
54 import android
.widget
.ArrayAdapter
;
55 import android
.widget
.TextView
;
56 import android
.widget
.Toast
;
58 import com
.actionbarsherlock
.app
.ActionBar
;
59 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
60 import com
.actionbarsherlock
.view
.Menu
;
61 import com
.actionbarsherlock
.view
.MenuInflater
;
62 import com
.actionbarsherlock
.view
.MenuItem
;
63 import com
.actionbarsherlock
.view
.Window
;
64 import com
.owncloud
.android
.BuildConfig
;
65 import com
.owncloud
.android
.MainApp
;
66 import com
.owncloud
.android
.R
;
67 import com
.owncloud
.android
.datamodel
.OCFile
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
;
69 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
76 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
77 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RenameFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
87 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
88 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
89 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
90 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
93 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
100 import com
.owncloud
.android
.utils
.DisplayUtils
;
101 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
102 import com
.owncloud
.android
.utils
.Log_OC
;
106 * Displays, what files the user has available in his ownCloud.
108 * @author Bartek Przybylski
109 * @author David A. Velasco
112 public class FileDisplayActivity
extends HookActivity
implements
113 FileFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
{
115 private ArrayAdapter
<String
> mDirectories
;
117 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
118 private UploadFinishReceiver mUploadFinishReceiver
;
119 private DownloadFinishReceiver mDownloadFinishReceiver
;
120 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
122 private boolean mDualPane
;
123 private View mLeftFragmentContainer
;
124 private View mRightFragmentContainer
;
126 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
127 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
128 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
130 public static final int DIALOG_SHORT_WAIT
= 0;
131 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
132 private static final int DIALOG_CERT_NOT_SAVED
= 2;
134 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
136 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
137 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
141 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
142 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
144 private OCFile mWaitingToPreview
;
146 private boolean mSyncInProgress
= false
;
148 private String DIALOG_UNTRUSTED_CERT
;
150 private OCFile mWaitingToSend
;
153 protected void onCreate(Bundle savedInstanceState
) {
154 Log_OC
.d(TAG
, "onCreate() start");
155 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
157 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
159 // PIN CODE request ; best location is to decide, let's try this first
160 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
162 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
166 /// grant that FileObserverService is watching favourite files
167 if (savedInstanceState
== null
) {
168 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
169 startService(initObserversIntent
);
172 /// Load of saved instance state
173 if(savedInstanceState
!= null
) {
174 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mWaitingToSend
= null
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
188 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
189 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
190 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
191 if (savedInstanceState
== null
) {
192 createMinFragments();
196 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
197 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
198 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
202 Log_OC
.d(TAG
, "onCreate() end");
206 protected void onStart() {
208 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
212 protected void onDestroy() {
213 Log_OC
.d(TAG
, "onDestroy() FileDisplyActivty");
214 // Log_OC.stopLogging();
219 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
222 protected void onAccountSet(boolean stateWasRecovered
) {
223 super.onAccountSet(stateWasRecovered
);
224 if (getAccount() != null
) {
225 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
226 OCFile file
= getFile();
227 // get parent from path
228 String parentPath
= "";
230 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
231 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
232 // get parent from path
233 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
234 if (getStorageManager().getFileByPath(parentPath
) == null
)
235 file
= null
; // not able to know the directory where the file is uploading
237 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
241 // fall back to root folder
242 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
245 setNavigationListWithFolder(file
);
247 if (!stateWasRecovered
) {
248 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
249 initFragmentsWithFile();
250 if (file
.isFolder()) {
251 startSyncFolderOperation(file
);
255 updateFragmentsVisibility(!file
.isFolder());
256 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
262 private void setNavigationListWithFolder(OCFile file
) {
263 mDirectories
.clear();
264 OCFile fileIt
= file
;
266 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
267 if (fileIt
.isFolder()) {
268 mDirectories
.add(fileIt
.getFileName());
270 // get parent from path
271 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
272 fileIt
= getStorageManager().getFileByPath(parentPath
);
274 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
278 private void createMinFragments() {
279 OCFileListFragment listOfFiles
= new OCFileListFragment();
280 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
281 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
282 transaction
.commit();
285 private void initFragmentsWithFile() {
286 if (getAccount() != null
&& getFile() != null
) {
288 OCFileListFragment listOfFiles
= getListOfFilesFragment();
289 if (listOfFiles
!= null
) {
290 listOfFiles
.listDirectory(getCurrentDir());
292 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
296 OCFile file
= getFile();
297 Fragment secondFragment
= chooseInitialSecondFragment(file
);
298 if (secondFragment
!= null
) {
299 setSecondFragment(secondFragment
);
300 updateFragmentsVisibility(true
);
301 updateNavigationElementsInActionBar(file
);
304 cleanSecondFragment();
308 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
309 if (getAccount() == null
) {
310 Log
.wtf(TAG
, "\t account is NULL");
312 if (getFile() == null
) {
313 Log
.wtf(TAG
, "\t file is NULL");
318 private Fragment
chooseInitialSecondFragment(OCFile file
) {
319 Fragment secondFragment
= null
;
320 if (file
!= null
&& !file
.isFolder()) {
321 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
322 && file
.getLastSyncDateForProperties() > 0 // temporal fix
324 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
325 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
326 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
329 secondFragment
= new FileDetailFragment(file
, getAccount());
332 return secondFragment
;
337 * Replaces the second fragment managed by the activity with the received as
340 * Assumes never will be more than two fragments managed at the same time.
342 * @param fragment New second Fragment to set.
344 private void setSecondFragment(Fragment fragment
) {
345 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
346 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
347 transaction
.commit();
351 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
353 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
354 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
356 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
357 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
360 } else if (existsSecondFragment
) {
361 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
362 mLeftFragmentContainer
.setVisibility(View
.GONE
);
364 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
369 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
372 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
373 mRightFragmentContainer
.setVisibility(View
.GONE
);
379 private OCFileListFragment
getListOfFilesFragment() {
380 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
381 if (listOfFiles
!= null
) {
382 return (OCFileListFragment
)listOfFiles
;
384 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
388 public FileFragment
getSecondFragment() {
389 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
390 if (second
!= null
) {
391 return (FileFragment
)second
;
396 protected void cleanSecondFragment() {
397 Fragment second
= getSecondFragment();
398 if (second
!= null
) {
399 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
403 updateFragmentsVisibility(false
);
404 updateNavigationElementsInActionBar(null
);
407 protected void refreshListOfFilesFragment() {
408 OCFileListFragment fileListFragment
= getListOfFilesFragment();
409 if (fileListFragment
!= null
) {
410 fileListFragment
.listDirectory();
414 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
415 FileFragment secondFragment
= getSecondFragment();
416 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
417 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
418 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
419 OCFile fileInFragment
= detailsFragment
.getFile();
420 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
421 // the user browsed to other file ; forget the automatic preview
422 mWaitingToPreview
= null
;
424 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
425 // grant that the right panel updates the progress bar
426 detailsFragment
.listenForTransferProgress();
427 detailsFragment
.updateFileDetails(true
, false
);
429 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
430 // update the right panel
431 boolean detailsFragmentChanged
= false
;
434 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
435 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
436 startMediaPreview(mWaitingToPreview
, 0, true
);
437 detailsFragmentChanged
= true
;
439 getFileOperationsHelper().openFile(mWaitingToPreview
);
442 mWaitingToPreview
= null
;
444 if (!detailsFragmentChanged
) {
445 detailsFragment
.updateFileDetails(false
, (success
));
452 public boolean onPrepareOptionsMenu(Menu menu
) {
453 if (BuildConfig
.DEBUG
) {
454 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
456 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
458 return super.onPrepareOptionsMenu(menu
);
462 public boolean onCreateOptionsMenu(Menu menu
) {
463 MenuInflater inflater
= getSherlock().getMenuInflater();
464 inflater
.inflate(R
.menu
.main_menu
, menu
);
469 public boolean onOptionsItemSelected(MenuItem item
) {
470 boolean retval
= true
;
471 switch (item
.getItemId()) {
472 case R
.id
.action_create_dir
: {
473 CreateFolderDialogFragment dialog
=
474 CreateFolderDialogFragment
.newInstance(getCurrentDir());
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 R
.id
.action_logger
: {
492 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
493 startActivity(loggerIntent
);
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 // refresh list of files
694 refreshListOfFilesFragment();
696 // Listen for sync messages
697 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
698 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
699 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
700 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
701 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
702 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
703 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
704 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
706 // Listen for upload messages
707 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
708 mUploadFinishReceiver
= new UploadFinishReceiver();
709 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
711 // Listen for download messages
712 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
713 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
714 mDownloadFinishReceiver
= new DownloadFinishReceiver();
715 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
717 Log_OC
.d(TAG
, "onResume() end");
722 protected void onPause() {
723 Log_OC
.e(TAG
, "onPause() start");
724 if (mSyncBroadcastReceiver
!= null
) {
725 unregisterReceiver(mSyncBroadcastReceiver
);
726 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
727 mSyncBroadcastReceiver
= null
;
729 if (mUploadFinishReceiver
!= null
) {
730 unregisterReceiver(mUploadFinishReceiver
);
731 mUploadFinishReceiver
= null
;
733 if (mDownloadFinishReceiver
!= null
) {
734 unregisterReceiver(mDownloadFinishReceiver
);
735 mDownloadFinishReceiver
= null
;
739 Log_OC
.d(TAG
, "onPause() end");
745 protected Dialog
onCreateDialog(int id
) {
746 Dialog dialog
= null
;
747 AlertDialog
.Builder builder
;
749 case DIALOG_SHORT_WAIT
: {
750 ProgressDialog working_dialog
= new ProgressDialog(this);
751 working_dialog
.setMessage(getResources().getString(
752 R
.string
.wait_a_moment
));
753 working_dialog
.setIndeterminate(true
);
754 working_dialog
.setCancelable(false
);
755 dialog
= working_dialog
;
758 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
761 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
762 getString(R
.string
.actionbar_upload_from_apps
) };
764 builder
= new AlertDialog
.Builder(this);
765 builder
.setTitle(R
.string
.actionbar_upload
);
766 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
767 public void onClick(DialogInterface dialog
, int item
) {
770 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
771 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
772 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
774 // TODO create and handle new fragment
775 // LocalFileListFragment
777 } else if (item
== 1) {
778 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
779 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
780 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
781 ACTION_SELECT_CONTENT_FROM_APPS
);
785 dialog
= builder
.create();
788 case DIALOG_CERT_NOT_SAVED
: {
789 builder
= new AlertDialog
.Builder(this);
790 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
791 builder
.setCancelable(false
);
792 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
794 public void onClick(DialogInterface dialog
, int which
) {
798 dialog
= builder
.create();
810 * Translates a content URI of an image to a physical path
812 * @param uri The URI to resolve
813 * @return The path to the image or null if it could not be found
815 public String
getPath(Uri uri
) {
816 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
817 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
818 if (cursor
!= null
) {
819 int column_index
= cursor
820 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
821 cursor
.moveToFirst();
822 return cursor
.getString(column_index
);
828 * Pushes a directory to the drop down list
829 * @param directory to push
830 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
832 public void pushDirname(OCFile directory
) {
833 if(!directory
.isFolder()){
834 throw new IllegalArgumentException("Only directories may be pushed!");
836 mDirectories
.insert(directory
.getFileName(), 0);
841 * Pops a directory name from the drop down list
842 * @return True, unless the stack is empty
844 public boolean popDirname() {
845 mDirectories
.remove(mDirectories
.getItem(0));
846 return !mDirectories
.isEmpty();
849 // Custom array adapter to override text colors
850 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
852 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
856 public View
getView(int position
, View convertView
, ViewGroup parent
) {
857 View v
= super.getView(position
, convertView
, parent
);
859 ((TextView
) v
).setTextColor(getResources().getColorStateList(
860 android
.R
.color
.white
));
862 fixRoot((TextView
) v
);
866 public View
getDropDownView(int position
, View convertView
,
868 View v
= super.getDropDownView(position
, convertView
, parent
);
870 ((TextView
) v
).setTextColor(getResources().getColorStateList(
871 android
.R
.color
.white
));
873 fixRoot((TextView
) v
);
877 private void fixRoot(TextView v
) {
878 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
879 v
.setText(R
.string
.default_display_name_for_root_folder
);
885 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
888 * {@link BroadcastReceiver} to enable syncing feedback in UI
891 public void onReceive(Context context
, Intent intent
) {
893 String event
= intent
.getAction();
894 Log_OC
.d(TAG
, "Received broadcast " + event
);
895 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
896 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
897 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
898 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
902 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
903 mSyncInProgress
= true
;
906 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
907 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
909 if (currentDir
== null
) {
910 // current folder was removed from the server
911 Toast
.makeText( FileDisplayActivity
.this,
912 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
918 if (currentFile
== null
&& !getFile().isFolder()) {
919 // currently selected file was removed in the server, and now we know it
920 cleanSecondFragment();
921 currentFile
= currentDir
;
924 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
925 OCFileListFragment fileListFragment
= getListOfFilesFragment();
926 if (fileListFragment
!= null
) {
927 fileListFragment
.listDirectory(currentDir
);
930 setFile(currentFile
);
933 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
935 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
937 /// TODO refactor and make common
938 synchResult
!= null
&& !synchResult
.isSuccess() &&
939 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
940 synchResult
.isIdPRedirection() ||
941 (synchResult
.isException() && synchResult
.getException()
942 instanceof AuthenticatorException
))) {
944 OwnCloudClient client
= null
;
946 OwnCloudAccount ocAccount
=
947 new OwnCloudAccount(getAccount(), context
);
948 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
949 removeClientFor(ocAccount
));
950 // TODO get rid of these exceptions
951 } catch (AccountNotFoundException e
) {
953 } catch (AuthenticatorException e
) {
955 } catch (OperationCanceledException e
) {
957 } catch (IOException e
) {
961 if (client
!= null
) {
962 OwnCloudCredentials cred
= client
.getCredentials();
964 AccountManager am
= AccountManager
.get(context
);
965 if (cred
.authTokenExpires()) {
966 am
.invalidateAuthToken(
971 am
.clearPassword(getAccount());
976 requestCredentialsUpdate();
980 removeStickyBroadcast(intent
);
981 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
982 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
988 if (synchResult
!= null
) {
989 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
990 mLastSslUntrustedServerResult
= synchResult
;
993 } catch (RuntimeException e
) {
994 // avoid app crashes after changing the serial id of RemoteOperationResult
995 // in owncloud library with broadcast notifications pending to process
996 removeStickyBroadcast(intent
);
1002 * Show a text message on screen view for notifying user if content is
1003 * loading or folder is empty
1005 private void setBackgroundText() {
1006 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1007 if (ocFileListFragment
!= null
) {
1008 int message
= R
.string
.file_list_loading
;
1009 if (!mSyncInProgress
) {
1010 // In case file list is empty
1011 message
= R
.string
.file_list_empty
;
1013 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1015 Log
.e(TAG
, "OCFileListFragment is null");
1020 * Once the file upload has finished -> update view
1022 private class UploadFinishReceiver
extends BroadcastReceiver
{
1024 * Once the file upload has finished -> update view
1025 * @author David A. Velasco
1026 * {@link BroadcastReceiver} to enable upload feedback in UI
1029 public void onReceive(Context context
, Intent intent
) {
1031 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1032 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1033 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1034 OCFile currentDir
= getCurrentDir();
1035 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1036 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1038 if (sameAccount
&& isDescendant
) {
1039 refreshListOfFilesFragment();
1042 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1043 boolean renamedInUpload
= getFile().getRemotePath().
1044 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1045 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1047 FileFragment details
= getSecondFragment();
1048 boolean detailFragmentIsShown
= (details
!= null
&&
1049 details
instanceof FileDetailFragment
);
1051 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1052 if (uploadWasFine
) {
1053 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1055 if (renamedInUpload
) {
1056 String newName
= (new File(uploadedRemotePath
)).getName();
1057 Toast msg
= Toast
.makeText(
1060 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1065 if (uploadWasFine
|| getFile().fileExists()) {
1066 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1068 cleanSecondFragment();
1071 // Force the preview if the file is an image
1072 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1073 startImagePreview(getFile());
1074 } // TODO what about other kind of previews?
1078 if (intent
!= null
) {
1079 removeStickyBroadcast(intent
);
1089 * Class waiting for broadcast events from the {@link FielDownloader} service.
1091 * Updates the UI when a download is started or finished, provided that it is relevant for the
1094 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1096 public void onReceive(Context context
, Intent intent
) {
1098 boolean sameAccount
= isSameAccount(context
, intent
);
1099 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1100 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1102 if (sameAccount
&& isDescendant
) {
1103 refreshListOfFilesFragment();
1104 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1107 if (mWaitingToSend
!= null
) {
1108 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1109 if (mWaitingToSend
.isDown()) {
1110 sendDownloadedFile();
1115 if (intent
!= null
) {
1116 removeStickyBroadcast(intent
);
1121 private boolean isDescendant(String downloadedRemotePath
) {
1122 OCFile currentDir
= getCurrentDir();
1123 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1126 private boolean isSameAccount(Context context
, Intent intent
) {
1127 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1128 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1133 public void browseToRoot() {
1134 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1135 if (listOfFiles
!= null
) { // should never be null, indeed
1136 while (mDirectories
.getCount() > 1) {
1139 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1140 listOfFiles
.listDirectory(root
);
1141 setFile(listOfFiles
.getCurrentFile());
1142 startSyncFolderOperation(root
);
1144 cleanSecondFragment();
1148 public void browseTo(OCFile folder
) {
1149 if (folder
== null
|| !folder
.isFolder()) {
1150 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1152 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1153 if (listOfFiles
!= null
) {
1154 setNavigationListWithFolder(folder
);
1155 listOfFiles
.listDirectory(folder
);
1156 setFile(listOfFiles
.getCurrentFile());
1157 startSyncFolderOperation(folder
);
1159 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1161 cleanSecondFragment();
1168 * Updates action bar and second fragment, if in dual pane mode.
1171 public void onBrowsedDownTo(OCFile directory
) {
1172 pushDirname(directory
);
1173 cleanSecondFragment();
1176 startSyncFolderOperation(directory
);
1181 * Shows the information of the {@link OCFile} received as a
1182 * parameter in the second fragment.
1184 * @param file {@link OCFile} whose details will be shown
1187 public void showDetails(OCFile file
) {
1188 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1189 setSecondFragment(detailFragment
);
1190 updateFragmentsVisibility(true
);
1191 updateNavigationElementsInActionBar(file
);
1199 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1200 ActionBar actionBar
= getSupportActionBar();
1201 if (chosenFile
== null
|| mDualPane
) {
1202 // only list of files - set for browsing through folders
1203 OCFile currentDir
= getCurrentDir();
1204 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1205 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1206 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1208 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1210 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1211 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1214 actionBar
.setDisplayHomeAsUpEnabled(true
);
1215 actionBar
.setDisplayShowTitleEnabled(true
);
1216 actionBar
.setTitle(chosenFile
.getFileName());
1217 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1223 protected ServiceConnection
newTransferenceServiceConnection() {
1224 return new ListServiceConnection();
1227 /** Defines callbacks for service binding, passed to bindService() */
1228 private class ListServiceConnection
implements ServiceConnection
{
1231 public void onServiceConnected(ComponentName component
, IBinder service
) {
1232 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1233 Log_OC
.d(TAG
, "Download service connected");
1234 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1235 if (mWaitingToPreview
!= null
)
1236 if (getStorageManager() != null
) {
1237 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1238 if (!mWaitingToPreview
.isDown()) {
1239 requestForDownload();
1243 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1244 Log_OC
.d(TAG
, "Upload service connected");
1245 mUploaderBinder
= (FileUploaderBinder
) service
;
1249 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1250 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1251 if (listOfFiles
!= null
) {
1252 listOfFiles
.listDirectory();
1254 FileFragment secondFragment
= getSecondFragment();
1255 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1256 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1257 detailFragment
.listenForTransferProgress();
1258 detailFragment
.updateFileDetails(false
, false
);
1263 public void onServiceDisconnected(ComponentName component
) {
1264 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1265 Log_OC
.d(TAG
, "Download service disconnected");
1266 mDownloaderBinder
= null
;
1267 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1268 Log_OC
.d(TAG
, "Upload service disconnected");
1269 mUploaderBinder
= null
;
1277 * Launch an intent to request the PIN code to the user before letting him use the app
1279 private void requestPinCode() {
1280 boolean pinStart
= false
;
1281 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1282 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1284 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1285 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1292 public void onSavedCertificate() {
1293 startSyncFolderOperation(getCurrentDir());
1298 public void onFailedSavingCertificate() {
1299 showDialog(DIALOG_CERT_NOT_SAVED
);
1303 public void onCancelCertificate() {
1308 * Updates the view associated to the activity after the finish of some operation over files
1309 * in the current account.
1311 * @param operation Removal operation performed.
1312 * @param result Result of the removal.
1315 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1316 super.onRemoteOperationFinish(operation
, result
);
1318 if (operation
instanceof RemoveFileOperation
) {
1319 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1321 } else if (operation
instanceof RenameFileOperation
) {
1322 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1324 } else if (operation
instanceof SynchronizeFileOperation
) {
1325 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1327 } else if (operation
instanceof CreateFolderOperation
) {
1328 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1330 } else if (operation
instanceof CreateShareOperation
) {
1331 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1333 } else if (operation
instanceof UnshareLinkOperation
) {
1334 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1341 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1342 if (result
.isSuccess()) {
1343 refreshShowDetails();
1344 refreshListOfFilesFragment();
1349 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1350 if (result
.isSuccess()) {
1351 refreshShowDetails();
1352 refreshListOfFilesFragment();
1354 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1355 cleanSecondFragment();
1356 refreshListOfFilesFragment();
1360 private void refreshShowDetails() {
1361 FileFragment details
= getSecondFragment();
1362 if (details
!= null
) {
1363 OCFile file
= details
.getFile();
1365 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1366 if (details
instanceof PreviewMediaFragment
) {
1367 // Refresh OCFile of the fragment
1368 ((PreviewMediaFragment
) details
).updateFile(file
);
1373 invalidateOptionsMenu();
1378 * Updates the view associated to the activity after the finish of an operation trying to remove a
1381 * @param operation Removal operation performed.
1382 * @param result Result of the removal.
1384 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1385 dismissLoadingDialog();
1387 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1391 if (result
.isSuccess()) {
1392 OCFile removedFile
= operation
.getFile();
1393 FileFragment second
= getSecondFragment();
1394 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1395 if (second
instanceof PreviewMediaFragment
) {
1396 ((PreviewMediaFragment
)second
).stopPreview(true
);
1398 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1399 cleanSecondFragment();
1401 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1402 refreshListOfFilesFragment();
1404 invalidateOptionsMenu();
1406 if (result
.isSslRecoverableException()) {
1407 mLastSslUntrustedServerResult
= result
;
1408 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1415 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1417 * @param operation Creation operation performed.
1418 * @param result Result of the creation.
1420 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1421 if (result
.isSuccess()) {
1422 dismissLoadingDialog();
1423 refreshListOfFilesFragment();
1425 dismissLoadingDialog();
1427 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1428 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1432 } catch (NotFoundException e
) {
1433 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1440 * Updates the view associated to the activity after the finish of an operation trying to rename a
1443 * @param operation Renaming operation performed.
1444 * @param result Result of the renaming.
1446 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1447 dismissLoadingDialog();
1448 OCFile renamedFile
= operation
.getFile();
1449 if (result
.isSuccess()) {
1450 FileFragment details
= getSecondFragment();
1451 if (details
!= null
) {
1452 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1453 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1454 showDetails(renamedFile
);
1456 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1457 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1458 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1459 int position
= ((PreviewMediaFragment
)details
).getPosition();
1460 startMediaPreview(renamedFile
, position
, true
);
1462 getFileOperationsHelper().openFile(renamedFile
);
1467 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1468 refreshListOfFilesFragment();
1472 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1476 if (result
.isSslRecoverableException()) {
1477 mLastSslUntrustedServerResult
= result
;
1478 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1483 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1484 dismissLoadingDialog();
1485 OCFile syncedFile
= operation
.getLocalFile();
1486 if (!result
.isSuccess()) {
1487 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1488 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1489 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1490 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1496 if (operation
.transferWasRequested()) {
1497 onTransferStateChanged(syncedFile
, true
, true
);
1500 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1512 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1513 refreshListOfFilesFragment();
1514 FileFragment details
= getSecondFragment();
1515 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1516 if (downloading
|| uploading
) {
1517 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1519 if (!file
.fileExists()) {
1520 cleanSecondFragment();
1522 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1530 private void requestForDownload() {
1531 Account account
= getAccount();
1532 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1533 Intent i
= new Intent(this, FileDownloader
.class);
1534 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1535 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1541 private OCFile
getCurrentDir() {
1542 OCFile file
= getFile();
1544 if (file
.isFolder()) {
1546 } else if (getStorageManager() != null
) {
1547 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1548 return getStorageManager().getFileByPath(parentPath
);
1554 public void startSyncFolderOperation(OCFile folder
) {
1555 long currentSyncTime
= System
.currentTimeMillis();
1557 mSyncInProgress
= true
;
1559 // perform folder synchronization
1560 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1563 getFileOperationsHelper().isSharedSupported(),
1564 getStorageManager(),
1566 getApplicationContext()
1568 synchFolderOp
.execute(getAccount(), this, null
, null
);
1570 setSupportProgressBarIndeterminateVisibility(true
);
1572 setBackgroundText();
1576 * Show untrusted cert dialog
1578 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1579 // Show a dialog with the certificate info
1580 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1581 FragmentManager fm
= getSupportFragmentManager();
1582 FragmentTransaction ft
= fm
.beginTransaction();
1583 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1586 private void requestForDownload(OCFile file
) {
1587 Account account
= getAccount();
1588 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1589 Intent i
= new Intent(this, FileDownloader
.class);
1590 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1591 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1596 private void sendDownloadedFile(){
1597 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1598 mWaitingToSend
= null
;
1603 * Requests the download of the received {@link OCFile} , updates the UI
1604 * to monitor the download progress and prepares the activity to send the file
1605 * when the download finishes.
1607 * @param file {@link OCFile} to download and preview.
1609 public void startDownloadForSending(OCFile file
) {
1610 mWaitingToSend
= file
;
1611 requestForDownload(mWaitingToSend
);
1612 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1613 updateFragmentsVisibility(hasSecondFragment
);
1617 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1619 * @param file Image {@link OCFile} to show.
1621 public void startImagePreview(OCFile file
) {
1622 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1623 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1624 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1625 startActivity(showDetailsIntent
);
1630 * Stars the preview of an already down media {@link OCFile}.
1632 * @param file Media {@link OCFile} to preview.
1633 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1634 * @param autoplay When 'true', the playback will start without user interactions.
1636 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1637 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1638 setSecondFragment(mediaFragment
);
1639 updateFragmentsVisibility(true
);
1640 updateNavigationElementsInActionBar(file
);
1645 * Requests the download of the received {@link OCFile} , updates the UI
1646 * to monitor the download progress and prepares the activity to preview
1647 * or open the file when the download finishes.
1649 * @param file {@link OCFile} to download and preview.
1651 public void startDownloadForPreview(OCFile file
) {
1652 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1653 setSecondFragment(detailFragment
);
1654 mWaitingToPreview
= file
;
1655 requestForDownload();
1656 updateFragmentsVisibility(true
);
1657 updateNavigationElementsInActionBar(file
);
1662 public void cancelTransference(OCFile file
) {
1663 getFileOperationsHelper().cancelTransference(file
);
1664 if (mWaitingToPreview
!= null
&&
1665 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1666 mWaitingToPreview
= null
;
1668 if (mWaitingToSend
!= null
&&
1669 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1670 mWaitingToSend
= null
;
1672 onTransferStateChanged(file
, false
, false
);