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 org
.apache
.commons
.httpclient
.Credentials
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.app
.AlertDialog
;
28 import android
.app
.Dialog
;
29 import android
.app
.ProgressDialog
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.ComponentName
;
32 import android
.content
.ContentResolver
;
33 import android
.content
.Context
;
34 import android
.content
.DialogInterface
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SyncRequest
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Bundle
;
44 import android
.os
.IBinder
;
45 import android
.preference
.PreferenceManager
;
46 import android
.provider
.MediaStore
;
47 import android
.support
.v4
.app
.Fragment
;
48 import android
.support
.v4
.app
.FragmentManager
;
49 import android
.support
.v4
.app
.FragmentTransaction
;
50 //import android.support.v4.content.LocalBroadcastManager;
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
.MainApp
;
65 import com
.owncloud
.android
.R
;
66 import com
.owncloud
.android
.datamodel
.OCFile
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
;
68 import com
.owncloud
.android
.files
.services
.FileObserverService
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
72 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClientMap
;
76 import com
.owncloud
.android
.lib
.common
.network
.BearerCredentials
;
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
.CreateShareOperation
;
82 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
83 import com
.owncloud
.android
.operations
.RenameFileOperation
;
84 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
86 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
87 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
88 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
89 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
91 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
92 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
94 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
98 import com
.owncloud
.android
.utils
.DisplayUtils
;
99 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
100 import com
.owncloud
.android
.utils
.Log_OC
;
104 * Displays, what files the user has available in his ownCloud.
106 * @author Bartek Przybylski
107 * @author David A. Velasco
110 public class FileDisplayActivity
extends HookActivity
implements
111 FileFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
{
113 private ArrayAdapter
<String
> mDirectories
;
115 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
116 private UploadFinishReceiver mUploadFinishReceiver
;
117 private DownloadFinishReceiver mDownloadFinishReceiver
;
118 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
120 private boolean mDualPane
;
121 private View mLeftFragmentContainer
;
122 private View mRightFragmentContainer
;
124 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
125 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
126 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
128 public static final int DIALOG_SHORT_WAIT
= 0;
129 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
130 private static final int DIALOG_CERT_NOT_SAVED
= 2;
132 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
134 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
135 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
137 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
139 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
140 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
142 private OCFile mWaitingToPreview
;
144 private boolean mSyncInProgress
= false
;
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 // PIN CODE request ; best location is to decide, let's try this first
158 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
160 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
165 Intent observer_intent
= new Intent(this, FileObserverService
.class);
166 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
167 startService(observer_intent
);
169 /// Load of saved instance state
170 if(savedInstanceState
!= null
) {
171 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
172 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
173 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
176 mWaitingToPreview
= null
;
177 mSyncInProgress
= false
;
178 mWaitingToSend
= null
;
183 // Inflate and set the layout view
184 setContentView(R
.layout
.files
);
185 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
186 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
187 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
188 if (savedInstanceState
== null
) {
189 createMinFragments();
193 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
194 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
195 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
197 Log_OC
.d(TAG
, "onCreate() end");
201 protected void onStart() {
203 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
207 protected void onDestroy() {
212 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
215 protected void onAccountSet(boolean stateWasRecovered
) {
216 super.onAccountSet(stateWasRecovered
);
217 if (getAccount() != null
) {
218 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
219 OCFile file
= getFile();
220 // get parent from path
221 String parentPath
= "";
223 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
224 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
225 // get parent from path
226 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
227 if (getStorageManager().getFileByPath(parentPath
) == null
)
228 file
= null
; // not able to know the directory where the file is uploading
230 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
234 // fall back to root folder
235 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
238 setNavigationListWithFolder(file
);
240 if (!stateWasRecovered
) {
241 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
242 initFragmentsWithFile();
243 if (file
.isFolder()) {
244 startSyncFolderOperation(file
);
248 updateFragmentsVisibility(!file
.isFolder());
249 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
255 private void setNavigationListWithFolder(OCFile file
) {
256 mDirectories
.clear();
257 OCFile fileIt
= file
;
259 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
260 if (fileIt
.isFolder()) {
261 mDirectories
.add(fileIt
.getFileName());
263 // get parent from path
264 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
265 fileIt
= getStorageManager().getFileByPath(parentPath
);
267 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
271 private void createMinFragments() {
272 OCFileListFragment listOfFiles
= new OCFileListFragment();
273 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
274 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
275 transaction
.commit();
278 private void initFragmentsWithFile() {
279 if (getAccount() != null
&& getFile() != null
) {
281 OCFileListFragment listOfFiles
= getListOfFilesFragment();
282 if (listOfFiles
!= null
) {
283 listOfFiles
.listDirectory(getCurrentDir());
285 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
289 OCFile file
= getFile();
290 Fragment secondFragment
= chooseInitialSecondFragment(file
);
291 if (secondFragment
!= null
) {
292 setSecondFragment(secondFragment
);
293 updateFragmentsVisibility(true
);
294 updateNavigationElementsInActionBar(file
);
297 cleanSecondFragment();
301 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
302 if (getAccount() == null
) {
303 Log
.wtf(TAG
, "\t account is NULL");
305 if (getFile() == null
) {
306 Log
.wtf(TAG
, "\t file is NULL");
311 private Fragment
chooseInitialSecondFragment(OCFile file
) {
312 Fragment secondFragment
= null
;
313 if (file
!= null
&& !file
.isFolder()) {
314 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
315 && file
.getLastSyncDateForProperties() > 0 // temporal fix
317 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
318 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
319 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
322 secondFragment
= new FileDetailFragment(file
, getAccount());
325 return secondFragment
;
330 * Replaces the second fragment managed by the activity with the received as
333 * Assumes never will be more than two fragments managed at the same time.
335 * @param fragment New second Fragment to set.
337 private void setSecondFragment(Fragment fragment
) {
338 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
339 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
340 transaction
.commit();
344 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
346 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
347 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
349 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
350 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
353 } else if (existsSecondFragment
) {
354 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
355 mLeftFragmentContainer
.setVisibility(View
.GONE
);
357 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
362 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
363 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
365 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
366 mRightFragmentContainer
.setVisibility(View
.GONE
);
372 private OCFileListFragment
getListOfFilesFragment() {
373 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
374 if (listOfFiles
!= null
) {
375 return (OCFileListFragment
)listOfFiles
;
377 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
381 public FileFragment
getSecondFragment() {
382 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
383 if (second
!= null
) {
384 return (FileFragment
)second
;
389 protected void cleanSecondFragment() {
390 Fragment second
= getSecondFragment();
391 if (second
!= null
) {
392 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
396 updateFragmentsVisibility(false
);
397 updateNavigationElementsInActionBar(null
);
400 protected void refreshListOfFilesFragment() {
401 OCFileListFragment fileListFragment
= getListOfFilesFragment();
402 if (fileListFragment
!= null
) {
403 fileListFragment
.listDirectory();
407 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
408 FileFragment secondFragment
= getSecondFragment();
409 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
410 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
411 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
412 OCFile fileInFragment
= detailsFragment
.getFile();
413 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
414 // the user browsed to other file ; forget the automatic preview
415 mWaitingToPreview
= null
;
417 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
418 // grant that the right panel updates the progress bar
419 detailsFragment
.listenForTransferProgress();
420 detailsFragment
.updateFileDetails(true
, false
);
422 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
423 // update the right panel
424 boolean detailsFragmentChanged
= false
;
427 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
428 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
429 startMediaPreview(mWaitingToPreview
, 0, true
);
430 detailsFragmentChanged
= true
;
432 getFileOperationsHelper().openFile(mWaitingToPreview
);
435 mWaitingToPreview
= null
;
437 if (!detailsFragmentChanged
) {
438 detailsFragment
.updateFileDetails(false
, (success
));
445 public boolean onCreateOptionsMenu(Menu menu
) {
446 MenuInflater inflater
= getSherlock().getMenuInflater();
447 inflater
.inflate(R
.menu
.main_menu
, menu
);
452 public boolean onOptionsItemSelected(MenuItem item
) {
453 boolean retval
= true
;
454 switch (item
.getItemId()) {
455 case R
.id
.action_create_dir
: {
456 CreateFolderDialogFragment dialog
=
457 CreateFolderDialogFragment
.newInstance(getCurrentDir());
458 dialog
.show(getSupportFragmentManager(), "createdirdialog");
461 case R
.id
.action_sync_account
: {
462 startSynchronization();
465 case R
.id
.action_upload
: {
466 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
469 case R
.id
.action_settings
: {
470 Intent settingsIntent
= new Intent(this, Preferences
.class);
471 startActivity(settingsIntent
);
474 case android
.R
.id
.home
: {
475 FileFragment second
= getSecondFragment();
476 OCFile currentDir
= getCurrentDir();
477 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
478 (second
!= null
&& second
.getFile() != null
)) {
485 retval
= super.onOptionsItemSelected(item
);
490 private void startSynchronization() {
491 Log_OC
.e(TAG
, "Got to start sync");
492 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
493 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
494 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
495 Bundle bundle
= new Bundle();
496 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
497 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
498 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
499 ContentResolver
.requestSync(
501 MainApp
.getAuthority(), bundle
);
503 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
504 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
505 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
506 builder
.setExpedited(true
);
507 builder
.setManual(true
);
509 SyncRequest request
= builder
.build();
510 ContentResolver
.requestSync(request
);
516 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
517 if (itemPosition
!= 0) {
518 String targetPath
= "";
519 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
520 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
522 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
523 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
524 if (targetFolder
!= null
) {
525 browseTo(targetFolder
);
528 // the next operation triggers a new call to this method, but it's necessary to
529 // ensure that the name exposed in the action bar is the current directory when the
530 // user selected it in the navigation list
531 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
532 getSupportActionBar().setSelectedNavigationItem(0);
538 * Called, when the user selected something for uploading
540 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
541 super.onActivityResult(requestCode
, resultCode
, data
);
543 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
544 requestSimpleUpload(data
, resultCode
);
546 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
547 requestMultipleUpload(data
, resultCode
);
552 private void requestMultipleUpload(Intent data
, int resultCode
) {
553 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
554 if (filePaths
!= null
) {
555 String
[] remotePaths
= new String
[filePaths
.length
];
556 String remotePathBase
= "";
557 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
558 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
560 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
561 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
562 for (int j
= 0; j
< remotePaths
.length
; j
++) {
563 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
566 Intent i
= new Intent(this, FileUploader
.class);
567 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
568 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
569 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
570 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
571 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
572 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
576 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
577 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
584 private void requestSimpleUpload(Intent data
, int resultCode
) {
585 String filepath
= null
;
587 Uri selectedImageUri
= data
.getData();
589 String filemanagerstring
= selectedImageUri
.getPath();
590 String selectedImagePath
= getPath(selectedImageUri
);
592 if (selectedImagePath
!= null
)
593 filepath
= selectedImagePath
;
595 filepath
= filemanagerstring
;
597 } catch (Exception e
) {
598 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
602 if (filepath
== null
) {
603 Log_OC
.e(TAG
, "Couldnt resolve path to file");
604 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
610 Intent i
= new Intent(this, FileUploader
.class);
611 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
613 String remotepath
= new String();
614 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
615 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
617 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
618 remotepath
+= OCFile
.PATH_SEPARATOR
;
619 remotepath
+= new File(filepath
).getName();
621 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
622 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
623 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
624 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
625 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
630 public void onBackPressed() {
631 OCFileListFragment listOfFiles
= getListOfFilesFragment();
632 if (mDualPane
|| getSecondFragment() == null
) {
633 if (listOfFiles
!= null
) { // should never be null, indeed
634 if (mDirectories
.getCount() <= 1) {
638 int levelsUp
= listOfFiles
.onBrowseUp();
639 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
644 if (listOfFiles
!= null
) { // should never be null, indeed
645 setFile(listOfFiles
.getCurrentFile());
647 cleanSecondFragment();
652 protected void onSaveInstanceState(Bundle outState
) {
653 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
654 Log_OC
.e(TAG
, "onSaveInstanceState() start");
655 super.onSaveInstanceState(outState
);
656 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
657 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
658 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
659 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
661 Log_OC
.d(TAG
, "onSaveInstanceState() end");
667 protected void onResume() {
669 Log_OC
.e(TAG
, "onResume() start");
671 // refresh list of files
672 refreshListOfFilesFragment();
674 // Listen for sync messages
675 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
676 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
677 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
678 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
679 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
680 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
681 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
682 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
684 // Listen for upload messages
685 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
686 mUploadFinishReceiver
= new UploadFinishReceiver();
687 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
689 // Listen for download messages
690 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
691 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
692 mDownloadFinishReceiver
= new DownloadFinishReceiver();
693 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
695 Log_OC
.d(TAG
, "onResume() end");
700 protected void onPause() {
701 Log_OC
.e(TAG
, "onPause() start");
702 if (mSyncBroadcastReceiver
!= null
) {
703 unregisterReceiver(mSyncBroadcastReceiver
);
704 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
705 mSyncBroadcastReceiver
= null
;
707 if (mUploadFinishReceiver
!= null
) {
708 unregisterReceiver(mUploadFinishReceiver
);
709 mUploadFinishReceiver
= null
;
711 if (mDownloadFinishReceiver
!= null
) {
712 unregisterReceiver(mDownloadFinishReceiver
);
713 mDownloadFinishReceiver
= null
;
717 Log_OC
.d(TAG
, "onPause() end");
723 protected Dialog
onCreateDialog(int id
) {
724 Dialog dialog
= null
;
725 AlertDialog
.Builder builder
;
727 case DIALOG_SHORT_WAIT
: {
728 ProgressDialog working_dialog
= new ProgressDialog(this);
729 working_dialog
.setMessage(getResources().getString(
730 R
.string
.wait_a_moment
));
731 working_dialog
.setIndeterminate(true
);
732 working_dialog
.setCancelable(false
);
733 dialog
= working_dialog
;
736 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
738 String
[] items
= null
;
740 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
741 getString(R
.string
.actionbar_upload_from_apps
),
742 getString(R
.string
.actionbar_failed_instant_upload
) };
744 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
745 getString(R
.string
.actionbar_upload_from_apps
) };
747 if (InstantUploadActivity
.IS_ENABLED
)
752 builder
= new AlertDialog
.Builder(this);
753 builder
.setTitle(R
.string
.actionbar_upload
);
754 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
755 public void onClick(DialogInterface dialog
, int item
) {
758 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
759 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
760 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
762 // TODO create and handle new fragment
763 // LocalFileListFragment
765 } else if (item
== 1) {
766 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
767 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
768 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
769 ACTION_SELECT_CONTENT_FROM_APPS
);
770 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
771 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
772 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
773 startActivity(action
);
777 dialog
= builder
.create();
780 case DIALOG_CERT_NOT_SAVED
: {
781 builder
= new AlertDialog
.Builder(this);
782 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
783 builder
.setCancelable(false
);
784 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
786 public void onClick(DialogInterface dialog
, int which
) {
790 dialog
= builder
.create();
802 * Translates a content URI of an image to a physical path
804 * @param uri The URI to resolve
805 * @return The path to the image or null if it could not be found
807 public String
getPath(Uri uri
) {
808 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
809 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
810 if (cursor
!= null
) {
811 int column_index
= cursor
812 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
813 cursor
.moveToFirst();
814 return cursor
.getString(column_index
);
820 * Pushes a directory to the drop down list
821 * @param directory to push
822 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
824 public void pushDirname(OCFile directory
) {
825 if(!directory
.isFolder()){
826 throw new IllegalArgumentException("Only directories may be pushed!");
828 mDirectories
.insert(directory
.getFileName(), 0);
833 * Pops a directory name from the drop down list
834 * @return True, unless the stack is empty
836 public boolean popDirname() {
837 mDirectories
.remove(mDirectories
.getItem(0));
838 return !mDirectories
.isEmpty();
841 // Custom array adapter to override text colors
842 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
844 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
848 public View
getView(int position
, View convertView
, ViewGroup parent
) {
849 View v
= super.getView(position
, convertView
, parent
);
851 ((TextView
) v
).setTextColor(getResources().getColorStateList(
852 android
.R
.color
.white
));
854 fixRoot((TextView
) v
);
858 public View
getDropDownView(int position
, View convertView
,
860 View v
= super.getDropDownView(position
, convertView
, parent
);
862 ((TextView
) v
).setTextColor(getResources().getColorStateList(
863 android
.R
.color
.white
));
865 fixRoot((TextView
) v
);
869 private void fixRoot(TextView v
) {
870 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
871 v
.setText(R
.string
.default_display_name_for_root_folder
);
877 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
880 * {@link BroadcastReceiver} to enable syncing feedback in UI
883 public void onReceive(Context context
, Intent intent
) {
885 String event
= intent
.getAction();
886 Log_OC
.d(TAG
, "Received broadcast " + event
);
887 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
888 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
889 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
890 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
894 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
895 mSyncInProgress
= true
;
898 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
899 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
901 if (currentDir
== null
) {
902 // current folder was removed from the server
903 Toast
.makeText( FileDisplayActivity
.this,
904 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
910 if (currentFile
== null
&& !getFile().isFolder()) {
911 // currently selected file was removed in the server, and now we know it
912 cleanSecondFragment();
913 currentFile
= currentDir
;
916 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
917 OCFileListFragment fileListFragment
= getListOfFilesFragment();
918 if (fileListFragment
!= null
) {
919 fileListFragment
.listDirectory(currentDir
);
922 setFile(currentFile
);
925 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
927 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
929 /// TODO refactor and make common
930 synchResult
!= null
&& !synchResult
.isSuccess() &&
931 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
932 synchResult
.isIdPRedirection() ||
933 (synchResult
.isException() && synchResult
.getException()
934 instanceof AuthenticatorException
))) {
937 OwnCloudClient client
= OwnCloudClientMap
.removeClientFor(getAccount());
938 if (client
!= null
) {
939 Credentials cred
= client
.getCredentials();
940 String ssoSessionCookie
= client
.getSsoSessionCookie();
941 if (cred
!= null
|| ssoSessionCookie
!= null
) {
942 boolean bearerAuthorization
= (cred
!= null
&& cred
instanceof BearerCredentials
);
943 boolean samlBasedSsoAuthorization
= (cred
== null
&& ssoSessionCookie
!= null
);
944 AccountManager am
= AccountManager
.get(context
);
946 if (bearerAuthorization
) {
947 am
.invalidateAuthToken(getAccount().type
,
948 ((BearerCredentials
)cred
).getAccessToken());
950 } else if (samlBasedSsoAuthorization
) {
951 am
.invalidateAuthToken(getAccount().type
, ssoSessionCookie
);
954 am
.clearPassword(getAccount());
959 requestCredentialsUpdate();
963 removeStickyBroadcast(intent
);
964 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
965 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
969 if (synchResult
!= null
) {
970 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
971 mLastSslUntrustedServerResult
= synchResult
;
974 } catch (RuntimeException e
) {
975 // avoid app crashes after changing the serial id of RemoteOperationResult
976 // in owncloud library with broadcast notifications pending to process
977 removeStickyBroadcast(intent
);
984 * Once the file upload has finished -> update view
986 private class UploadFinishReceiver
extends BroadcastReceiver
{
988 * Once the file upload has finished -> update view
989 * @author David A. Velasco
990 * {@link BroadcastReceiver} to enable upload feedback in UI
993 public void onReceive(Context context
, Intent intent
) {
994 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
995 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
996 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
997 OCFile currentDir
= getCurrentDir();
998 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
999 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1001 if (sameAccount
&& isDescendant
) {
1002 refreshListOfFilesFragment();
1005 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1006 boolean renamedInUpload
= getFile().getRemotePath().
1007 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1008 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1010 FileFragment details
= getSecondFragment();
1011 boolean detailFragmentIsShown
= (details
!= null
&&
1012 details
instanceof FileDetailFragment
);
1014 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1015 if (uploadWasFine
) {
1016 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1018 if (renamedInUpload
) {
1019 String newName
= (new File(uploadedRemotePath
)).getName();
1020 Toast msg
= Toast
.makeText(
1023 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1028 if (uploadWasFine
|| getFile().fileExists()) {
1029 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1031 cleanSecondFragment();
1034 // Force the preview if the file is an image
1035 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1036 startImagePreview(getFile());
1037 } // TODO what about other kind of previews?
1040 removeStickyBroadcast(intent
);
1048 * Class waiting for broadcast events from the {@link FielDownloader} service.
1050 * Updates the UI when a download is started or finished, provided that it is relevant for the
1053 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1055 public void onReceive(Context context
, Intent intent
) {
1056 boolean sameAccount
= isSameAccount(context
, intent
);
1057 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1058 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1060 if (sameAccount
&& isDescendant
) {
1061 refreshListOfFilesFragment();
1062 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1065 if (mWaitingToSend
!= null
) {
1066 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1067 if (mWaitingToSend
.isDown()) {
1068 sendDownloadedFile();
1072 removeStickyBroadcast(intent
);
1075 private boolean isDescendant(String downloadedRemotePath
) {
1076 OCFile currentDir
= getCurrentDir();
1077 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1080 private boolean isSameAccount(Context context
, Intent intent
) {
1081 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1082 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1087 public void browseToRoot() {
1088 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1089 if (listOfFiles
!= null
) { // should never be null, indeed
1090 while (mDirectories
.getCount() > 1) {
1093 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1094 listOfFiles
.listDirectory(root
);
1095 setFile(listOfFiles
.getCurrentFile());
1096 startSyncFolderOperation(root
);
1098 cleanSecondFragment();
1102 public void browseTo(OCFile folder
) {
1103 if (folder
== null
|| !folder
.isFolder()) {
1104 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1106 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1107 if (listOfFiles
!= null
) {
1108 setNavigationListWithFolder(folder
);
1109 listOfFiles
.listDirectory(folder
);
1110 setFile(listOfFiles
.getCurrentFile());
1111 startSyncFolderOperation(folder
);
1113 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1115 cleanSecondFragment();
1122 * Updates action bar and second fragment, if in dual pane mode.
1125 public void onBrowsedDownTo(OCFile directory
) {
1126 pushDirname(directory
);
1127 cleanSecondFragment();
1130 startSyncFolderOperation(directory
);
1135 * Shows the information of the {@link OCFile} received as a
1136 * parameter in the second fragment.
1138 * @param file {@link OCFile} whose details will be shown
1141 public void showDetails(OCFile file
) {
1142 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1143 setSecondFragment(detailFragment
);
1144 updateFragmentsVisibility(true
);
1145 updateNavigationElementsInActionBar(file
);
1153 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1154 ActionBar actionBar
= getSupportActionBar();
1155 if (chosenFile
== null
|| mDualPane
) {
1156 // only list of files - set for browsing through folders
1157 OCFile currentDir
= getCurrentDir();
1158 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1159 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1160 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1162 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1164 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1165 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1168 actionBar
.setDisplayHomeAsUpEnabled(true
);
1169 actionBar
.setDisplayShowTitleEnabled(true
);
1170 actionBar
.setTitle(chosenFile
.getFileName());
1171 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1177 protected ServiceConnection
newTransferenceServiceConnection() {
1178 return new ListServiceConnection();
1181 /** Defines callbacks for service binding, passed to bindService() */
1182 private class ListServiceConnection
implements ServiceConnection
{
1185 public void onServiceConnected(ComponentName component
, IBinder service
) {
1186 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1187 Log_OC
.d(TAG
, "Download service connected");
1188 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1189 if (mWaitingToPreview
!= null
)
1190 if (getStorageManager() != null
) {
1191 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1192 if (!mWaitingToPreview
.isDown()) {
1193 requestForDownload();
1197 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1198 Log_OC
.d(TAG
, "Upload service connected");
1199 mUploaderBinder
= (FileUploaderBinder
) service
;
1203 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1204 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1205 if (listOfFiles
!= null
) {
1206 listOfFiles
.listDirectory();
1208 FileFragment secondFragment
= getSecondFragment();
1209 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1210 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1211 detailFragment
.listenForTransferProgress();
1212 detailFragment
.updateFileDetails(false
, false
);
1217 public void onServiceDisconnected(ComponentName component
) {
1218 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1219 Log_OC
.d(TAG
, "Download service disconnected");
1220 mDownloaderBinder
= null
;
1221 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1222 Log_OC
.d(TAG
, "Upload service disconnected");
1223 mUploaderBinder
= null
;
1231 * Launch an intent to request the PIN code to the user before letting him use the app
1233 private void requestPinCode() {
1234 boolean pinStart
= false
;
1235 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1236 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1238 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1239 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1246 public void onSavedCertificate() {
1247 startSyncFolderOperation(getCurrentDir());
1252 public void onFailedSavingCertificate() {
1253 showDialog(DIALOG_CERT_NOT_SAVED
);
1257 public void onCancelCertificate() {
1262 * Updates the view associated to the activity after the finish of some operation over files
1263 * in the current account.
1265 * @param operation Removal operation performed.
1266 * @param result Result of the removal.
1269 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1270 super.onRemoteOperationFinish(operation
, result
);
1272 if (operation
instanceof RemoveFileOperation
) {
1273 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1275 } else if (operation
instanceof RenameFileOperation
) {
1276 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1278 } else if (operation
instanceof SynchronizeFileOperation
) {
1279 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1281 } else if (operation
instanceof CreateFolderOperation
) {
1282 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1284 } else if (operation
instanceof CreateShareOperation
) {
1285 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1287 } else if (operation
instanceof UnshareLinkOperation
) {
1288 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1295 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1296 if (result
.isSuccess()) {
1297 refreshShowDetails();
1298 refreshListOfFilesFragment();
1303 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1304 if (result
.isSuccess()) {
1305 refreshShowDetails();
1306 refreshListOfFilesFragment();
1308 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1309 cleanSecondFragment();
1310 refreshListOfFilesFragment();
1314 private void refreshShowDetails() {
1315 FileFragment details
= getSecondFragment();
1316 if (details
!= null
) {
1317 OCFile file
= details
.getFile();
1319 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1320 if (details
instanceof PreviewMediaFragment
) {
1321 // Refresh OCFile of the fragment
1322 ((PreviewMediaFragment
) details
).updateFile(file
);
1327 invalidateOptionsMenu();
1332 * Updates the view associated to the activity after the finish of an operation trying to remove a
1335 * @param operation Removal operation performed.
1336 * @param result Result of the removal.
1338 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1339 dismissLoadingDialog();
1341 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1345 if (result
.isSuccess()) {
1346 OCFile removedFile
= operation
.getFile();
1347 FileFragment second
= getSecondFragment();
1348 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1349 if (second
instanceof PreviewMediaFragment
) {
1350 ((PreviewMediaFragment
)second
).stopPreview(true
);
1352 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1353 cleanSecondFragment();
1355 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1356 refreshListOfFilesFragment();
1358 invalidateOptionsMenu();
1360 if (result
.isSslRecoverableException()) {
1361 mLastSslUntrustedServerResult
= result
;
1362 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1369 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1371 * @param operation Creation operation performed.
1372 * @param result Result of the creation.
1374 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1375 if (result
.isSuccess()) {
1376 dismissLoadingDialog();
1377 refreshListOfFilesFragment();
1379 dismissLoadingDialog();
1381 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1382 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1386 } catch (NotFoundException e
) {
1387 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1394 * Updates the view associated to the activity after the finish of an operation trying to rename a
1397 * @param operation Renaming operation performed.
1398 * @param result Result of the renaming.
1400 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1401 dismissLoadingDialog();
1402 OCFile renamedFile
= operation
.getFile();
1403 if (result
.isSuccess()) {
1404 FileFragment details
= getSecondFragment();
1405 if (details
!= null
) {
1406 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1407 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1408 showDetails(renamedFile
);
1410 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1411 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1412 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1413 int position
= ((PreviewMediaFragment
)details
).getPosition();
1414 startMediaPreview(renamedFile
, position
, true
);
1416 getFileOperationsHelper().openFile(renamedFile
);
1421 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1422 refreshListOfFilesFragment();
1426 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1430 if (result
.isSslRecoverableException()) {
1431 mLastSslUntrustedServerResult
= result
;
1432 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1437 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1438 dismissLoadingDialog();
1439 OCFile syncedFile
= operation
.getLocalFile();
1440 if (!result
.isSuccess()) {
1441 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1442 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1443 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1444 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1450 if (operation
.transferWasRequested()) {
1451 onTransferStateChanged(syncedFile
, true
, true
);
1454 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1466 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1467 refreshListOfFilesFragment();
1468 FileFragment details
= getSecondFragment();
1469 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1470 if (downloading
|| uploading
) {
1471 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1473 if (!file
.fileExists()) {
1474 cleanSecondFragment();
1476 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1484 private void requestForDownload() {
1485 Account account
= getAccount();
1486 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1487 Intent i
= new Intent(this, FileDownloader
.class);
1488 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1489 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1495 private OCFile
getCurrentDir() {
1496 OCFile file
= getFile();
1498 if (file
.isFolder()) {
1500 } else if (getStorageManager() != null
) {
1501 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1502 return getStorageManager().getFileByPath(parentPath
);
1508 public void startSyncFolderOperation(OCFile folder
) {
1509 long currentSyncTime
= System
.currentTimeMillis();
1511 mSyncInProgress
= true
;
1513 // perform folder synchronization
1514 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1517 getFileOperationsHelper().isSharedSupported(),
1518 getStorageManager(),
1520 getApplicationContext()
1522 synchFolderOp
.execute(getAccount(), this, null
, null
);
1524 setSupportProgressBarIndeterminateVisibility(true
);
1528 * Show untrusted cert dialog
1530 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1531 // Show a dialog with the certificate info
1532 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1533 FragmentManager fm
= getSupportFragmentManager();
1534 FragmentTransaction ft
= fm
.beginTransaction();
1535 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1538 private void requestForDownload(OCFile file
) {
1539 Account account
= getAccount();
1540 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1541 Intent i
= new Intent(this, FileDownloader
.class);
1542 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1543 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1548 private void sendDownloadedFile(){
1549 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1550 mWaitingToSend
= null
;
1555 * Requests the download of the received {@link OCFile} , updates the UI
1556 * to monitor the download progress and prepares the activity to send the file
1557 * when the download finishes.
1559 * @param file {@link OCFile} to download and preview.
1561 public void startDownloadForSending(OCFile file
) {
1562 mWaitingToSend
= file
;
1563 requestForDownload(mWaitingToSend
);
1564 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1565 updateFragmentsVisibility(hasSecondFragment
);
1569 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1571 * @param file Image {@link OCFile} to show.
1573 public void startImagePreview(OCFile file
) {
1574 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1575 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1576 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1577 startActivity(showDetailsIntent
);
1582 * Stars the preview of an already down media {@link OCFile}.
1584 * @param file Media {@link OCFile} to preview.
1585 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1586 * @param autoplay When 'true', the playback will start without user interactions.
1588 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1589 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1590 setSecondFragment(mediaFragment
);
1591 updateFragmentsVisibility(true
);
1592 updateNavigationElementsInActionBar(file
);
1597 * Requests the download of the received {@link OCFile} , updates the UI
1598 * to monitor the download progress and prepares the activity to preview
1599 * or open the file when the download finishes.
1601 * @param file {@link OCFile} to download and preview.
1603 public void startDownloadForPreview(OCFile file
) {
1604 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1605 setSecondFragment(detailFragment
);
1606 mWaitingToPreview
= file
;
1607 requestForDownload();
1608 updateFragmentsVisibility(true
);
1609 updateNavigationElementsInActionBar(file
);
1614 public void cancelTransference(OCFile file
) {
1615 getFileOperationsHelper().cancelTransference(file
);
1616 if (mWaitingToPreview
!= null
&&
1617 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1618 mWaitingToPreview
= null
;
1620 if (mWaitingToSend
!= null
&&
1621 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1622 mWaitingToSend
= null
;
1624 onTransferStateChanged(file
, false
, false
);