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
;
21 import android
.accounts
.Account
;
22 import android
.accounts
.AccountManager
;
23 import android
.accounts
.AuthenticatorException
;
24 import android
.accounts
.OperationCanceledException
;
25 import android
.app
.AlertDialog
;
26 import android
.app
.Dialog
;
27 import android
.app
.ProgressDialog
;
28 import android
.content
.BroadcastReceiver
;
29 import android
.content
.ComponentName
;
30 import android
.content
.ContentResolver
;
31 import android
.content
.Context
;
32 import android
.content
.DialogInterface
;
33 import android
.content
.Intent
;
34 import android
.content
.IntentFilter
;
35 import android
.content
.ServiceConnection
;
36 import android
.content
.SharedPreferences
;
37 import android
.content
.SyncRequest
;
38 import android
.content
.res
.Resources
.NotFoundException
;
39 import android
.database
.Cursor
;
40 import android
.net
.Uri
;
41 import android
.os
.Bundle
;
42 import android
.os
.IBinder
;
43 import android
.preference
.PreferenceManager
;
44 import android
.provider
.MediaStore
;
45 import android
.support
.v4
.app
.Fragment
;
46 import android
.support
.v4
.app
.FragmentManager
;
47 import android
.support
.v4
.app
.FragmentTransaction
;
48 import android
.view
.View
;
49 import android
.view
.ViewGroup
;
50 import android
.widget
.ArrayAdapter
;
51 import android
.widget
.TextView
;
52 import android
.widget
.Toast
;
54 import com
.actionbarsherlock
.app
.ActionBar
;
55 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
56 import com
.actionbarsherlock
.view
.Menu
;
57 import com
.actionbarsherlock
.view
.MenuInflater
;
58 import com
.actionbarsherlock
.view
.MenuItem
;
59 import com
.actionbarsherlock
.view
.Window
;
60 import com
.owncloud
.android
.BuildConfig
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
68 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
69 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
72 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
73 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
77 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
78 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
79 import com
.owncloud
.android
.operations
.CreateShareOperation
;
80 import com
.owncloud
.android
.operations
.MoveFileOperation
;
81 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
82 import com
.owncloud
.android
.operations
.RenameFileOperation
;
83 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
84 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
85 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
86 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
87 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
88 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
89 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
92 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
100 import com
.owncloud
.android
.utils
.DisplayUtils
;
101 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
104 import java
.io
.IOException
;
108 * Displays, what files the user has available in his ownCloud.
110 * @author Bartek Przybylski
111 * @author David A. Velasco
114 public class FileDisplayActivity
extends HookActivity
implements
115 FileFragment
.ContainerActivity
, OnNavigationListener
,
116 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
118 private ArrayAdapter
<String
> mDirectories
;
120 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
121 private UploadFinishReceiver mUploadFinishReceiver
;
122 private DownloadFinishReceiver mDownloadFinishReceiver
;
123 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
125 private boolean mDualPane
;
126 private View mLeftFragmentContainer
;
127 private View mRightFragmentContainer
;
129 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
130 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
131 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
133 public static final int DIALOG_SHORT_WAIT
= 0;
134 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
135 private static final int DIALOG_CERT_NOT_SAVED
= 2;
137 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
139 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
140 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
141 public static final int ACTION_MOVE_FILES
= 3;
143 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
145 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
146 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
148 private OCFile mWaitingToPreview
;
150 private boolean mSyncInProgress
= false
;
152 private String DIALOG_UNTRUSTED_CERT
;
154 private OCFile mWaitingToSend
;
157 protected void onCreate(Bundle savedInstanceState
) {
158 Log_OC
.d(TAG
, "onCreate() start");
159 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
161 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
163 // PIN CODE request ; best location is to decide, let's try this first
164 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
166 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
170 /// grant that FileObserverService is watching favourite files
171 if (savedInstanceState
== null
) {
172 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
173 startService(initObserversIntent
);
176 /// Load of saved instance state
177 if (savedInstanceState
!= null
) {
178 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
179 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
180 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
183 mWaitingToPreview
= null
;
184 mSyncInProgress
= false
;
185 mWaitingToSend
= null
;
190 // Inflate and set the layout view
191 setContentView(R
.layout
.files
);
192 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
193 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
194 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
195 if (savedInstanceState
== null
) {
196 createMinFragments();
200 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
201 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
202 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
206 Log_OC
.d(TAG
, "onCreate() end");
210 protected void onStart() {
212 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
216 protected void onDestroy() {
221 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
224 protected void onAccountSet(boolean stateWasRecovered
) {
225 super.onAccountSet(stateWasRecovered
);
226 if (getAccount() != null
) {
227 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
228 OCFile file
= getFile();
229 // get parent from path
230 String parentPath
= "";
232 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
233 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
234 // get parent from path
235 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
236 if (getStorageManager().getFileByPath(parentPath
) == null
)
237 file
= null
; // not able to know the directory where the file is uploading
239 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
243 // fall back to root folder
244 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
247 setNavigationListWithFolder(file
);
249 if (!stateWasRecovered
) {
250 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
251 initFragmentsWithFile();
252 if (file
.isFolder()) {
253 startSyncFolderOperation(file
, false
);
257 updateFragmentsVisibility(!file
.isFolder());
258 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
264 private void setNavigationListWithFolder(OCFile file
) {
265 mDirectories
.clear();
266 OCFile fileIt
= file
;
268 while (fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
269 if (fileIt
.isFolder()) {
270 mDirectories
.add(fileIt
.getFileName());
272 // get parent from path
273 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
274 fileIt
= getStorageManager().getFileByPath(parentPath
);
276 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
280 private void createMinFragments() {
281 OCFileListFragment listOfFiles
= new OCFileListFragment();
282 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
283 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
284 transaction
.commit();
287 private void initFragmentsWithFile() {
288 if (getAccount() != null
&& getFile() != null
) {
290 OCFileListFragment listOfFiles
= getListOfFilesFragment();
291 if (listOfFiles
!= null
) {
292 listOfFiles
.listDirectory(getCurrentDir());
294 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
298 OCFile file
= getFile();
299 Fragment secondFragment
= chooseInitialSecondFragment(file
);
300 if (secondFragment
!= null
) {
301 setSecondFragment(secondFragment
);
302 updateFragmentsVisibility(true
);
303 updateNavigationElementsInActionBar(file
);
306 cleanSecondFragment();
307 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
308 startTextPreview(file
);
312 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
313 if (getAccount() == null
) {
314 Log_OC
.wtf(TAG
, "\t account is NULL");
316 if (getFile() == null
) {
317 Log_OC
.wtf(TAG
, "\t file is NULL");
322 private Fragment
chooseInitialSecondFragment(OCFile file
) {
323 Fragment secondFragment
= null
;
324 if (file
!= null
&& !file
.isFolder()) {
325 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
326 && file
.getLastSyncDateForProperties() > 0 // temporal fix
328 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
329 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
330 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
332 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
333 secondFragment
= null
;
334 } else secondFragment
= new FileDetailFragment(file
, getAccount());
336 return secondFragment
;
341 * Replaces the second fragment managed by the activity with the received as
344 * Assumes never will be more than two fragments managed at the same time.
346 * @param fragment New second Fragment to set.
348 private void setSecondFragment(Fragment fragment
) {
349 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
350 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
351 transaction
.commit();
355 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
357 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
360 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
361 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
364 } else if (existsSecondFragment
) {
365 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
366 mLeftFragmentContainer
.setVisibility(View
.GONE
);
368 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
376 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
377 mRightFragmentContainer
.setVisibility(View
.GONE
);
383 private OCFileListFragment
getListOfFilesFragment() {
384 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
385 if (listOfFiles
!= null
) {
386 return (OCFileListFragment
) listOfFiles
;
388 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
392 public FileFragment
getSecondFragment() {
393 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
394 if (second
!= null
) {
395 return (FileFragment
) second
;
400 protected void cleanSecondFragment() {
401 Fragment second
= getSecondFragment();
402 if (second
!= null
) {
403 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
407 updateFragmentsVisibility(false
);
408 updateNavigationElementsInActionBar(null
);
411 protected void refreshListOfFilesFragment() {
412 OCFileListFragment fileListFragment
= getListOfFilesFragment();
413 if (fileListFragment
!= null
) {
414 fileListFragment
.listDirectory();
418 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
419 FileFragment secondFragment
= getSecondFragment();
420 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
421 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
422 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
423 OCFile fileInFragment
= detailsFragment
.getFile();
424 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
425 // the user browsed to other file ; forget the automatic preview
426 mWaitingToPreview
= null
;
428 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
429 // grant that the right panel updates the progress bar
430 detailsFragment
.listenForTransferProgress();
431 detailsFragment
.updateFileDetails(true
, false
);
433 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
434 // update the right panel
435 boolean detailsFragmentChanged
= false
;
438 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
439 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
440 startMediaPreview(mWaitingToPreview
, 0, true
);
441 detailsFragmentChanged
= true
;
442 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
443 startTextPreview(mWaitingToPreview
);
444 detailsFragmentChanged
= true
;
446 getFileOperationsHelper().openFile(mWaitingToPreview
);
449 mWaitingToPreview
= null
;
451 if (!detailsFragmentChanged
) {
452 detailsFragment
.updateFileDetails(false
, (success
));
459 public boolean onPrepareOptionsMenu(Menu menu
) {
460 if (BuildConfig
.DEBUG
) {
461 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
463 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
465 return super.onPrepareOptionsMenu(menu
);
469 public boolean onCreateOptionsMenu(Menu menu
) {
470 MenuInflater inflater
= getSherlock().getMenuInflater();
471 inflater
.inflate(R
.menu
.main_menu
, menu
);
476 public boolean onOptionsItemSelected(MenuItem item
) {
477 boolean retval
= true
;
478 switch (item
.getItemId()) {
479 case R
.id
.action_create_dir
: {
480 CreateFolderDialogFragment dialog
=
481 CreateFolderDialogFragment
.newInstance(getCurrentDir());
482 dialog
.show(getSupportFragmentManager(), "createdirdialog");
485 case R
.id
.action_sort
: {
486 SharedPreferences appPreferences
= PreferenceManager
487 .getDefaultSharedPreferences(this);
489 // Read sorting order, default to sort by name ascending
490 Integer sortOrder
= appPreferences
491 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
493 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
494 builder
.setTitle(R
.string
.actionbar_sort_title
)
495 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
496 public void onClick(DialogInterface dialog
, int which
) {
506 // TODO re-enable when server-side folder size calculation is available
508 // sortBySize(false);
516 builder
.create().show();
519 case R
.id
.action_sync_account
: {
520 startSynchronization();
523 case R
.id
.action_upload
: {
524 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
527 case R
.id
.action_settings
: {
528 Intent settingsIntent
= new Intent(this, Preferences
.class);
529 startActivity(settingsIntent
);
532 case R
.id
.action_logger
: {
533 Intent loggerIntent
= new Intent(getApplicationContext(), LogHistoryActivity
.class);
534 startActivity(loggerIntent
);
537 case android
.R
.id
.home
: {
538 FileFragment second
= getSecondFragment();
539 OCFile currentDir
= getCurrentDir();
540 if ((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
541 (second
!= null
&& second
.getFile() != null
)) {
548 retval
= super.onOptionsItemSelected(item
);
553 private void startSynchronization() {
554 Log_OC
.e(TAG
, "Got to start sync");
555 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
556 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
557 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
558 Bundle bundle
= new Bundle();
559 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
560 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
561 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
562 ContentResolver
.requestSync(
564 MainApp
.getAuthority(), bundle
);
566 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
567 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
568 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
569 builder
.setExpedited(true
);
570 builder
.setManual(true
);
572 SyncRequest request
= builder
.build();
573 ContentResolver
.requestSync(request
);
579 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
580 if (itemPosition
!= 0) {
581 String targetPath
= "";
582 for (int i
= itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
583 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
585 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
586 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
587 if (targetFolder
!= null
) {
588 browseTo(targetFolder
);
591 // the next operation triggers a new call to this method, but it's necessary to
592 // ensure that the name exposed in the action bar is the current directory when the
593 // user selected it in the navigation list
594 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
595 getSupportActionBar().setSelectedNavigationItem(0);
601 * Called, when the user selected something for uploading
603 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
604 super.onActivityResult(requestCode
, resultCode
, data
);
606 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
607 requestSimpleUpload(data
, resultCode
);
609 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
610 requestMultipleUpload(data
, resultCode
);
612 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
613 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)) {
615 final Intent fData
= data
;
616 final int fResultCode
= resultCode
;
617 getHandler().postDelayed(
621 requestMoveOperation(fData
, fResultCode
);
624 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
629 private void requestMultipleUpload(Intent data
, int resultCode
) {
630 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
631 if (filePaths
!= null
) {
632 String
[] remotePaths
= new String
[filePaths
.length
];
633 String remotePathBase
= "";
634 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
635 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
637 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
638 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
639 for (int j
= 0; j
< remotePaths
.length
; j
++) {
640 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
643 Intent i
= new Intent(this, FileUploader
.class);
644 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
645 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
646 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
647 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
648 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
649 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
653 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
654 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
661 private void requestSimpleUpload(Intent data
, int resultCode
) {
662 String filepath
= null
;
664 Uri selectedImageUri
= data
.getData();
666 String filemanagerstring
= selectedImageUri
.getPath();
667 String selectedImagePath
= getPath(selectedImageUri
);
669 if (selectedImagePath
!= null
)
670 filepath
= selectedImagePath
;
672 filepath
= filemanagerstring
;
674 } catch (Exception e
) {
675 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
679 if (filepath
== null
) {
680 Log_OC
.e(TAG
, "Couldnt resolve path to file");
681 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
687 Intent i
= new Intent(this, FileUploader
.class);
688 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
690 String remotepath
= new String();
691 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
692 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
694 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
695 remotepath
+= OCFile
.PATH_SEPARATOR
;
696 remotepath
+= new File(filepath
).getName();
698 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
699 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
700 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
701 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
702 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
707 * Request the operation for moving the file/folder from one path to another
709 * @param data Intent received
710 * @param resultCode Result code received
712 private void requestMoveOperation(Intent data
, int resultCode
) {
713 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
714 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
715 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
719 public void onBackPressed() {
720 OCFileListFragment listOfFiles
= getListOfFilesFragment();
721 if (mDualPane
|| getSecondFragment() == null
) {
722 if (listOfFiles
!= null
) { // should never be null, indeed
723 if (mDirectories
.getCount() <= 1) {
727 int levelsUp
= listOfFiles
.onBrowseUp();
728 for (int i
= 0; i
< levelsUp
&& mDirectories
.getCount() > 1; i
++) {
733 if (listOfFiles
!= null
) { // should never be null, indeed
734 setFile(listOfFiles
.getCurrentFile());
736 cleanSecondFragment();
741 protected void onSaveInstanceState(Bundle outState
) {
742 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
743 Log_OC
.e(TAG
, "onSaveInstanceState() start");
744 super.onSaveInstanceState(outState
);
745 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
746 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
747 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
748 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
750 Log_OC
.d(TAG
, "onSaveInstanceState() end");
755 protected void onResume() {
757 Log_OC
.e(TAG
, "onResume() start");
759 // refresh list of files
760 refreshListOfFilesFragment();
762 // Listen for sync messages
763 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
764 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
765 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
766 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
767 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
768 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
769 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
770 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
772 // Listen for upload messages
773 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
774 mUploadFinishReceiver
= new UploadFinishReceiver();
775 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
777 // Listen for download messages
778 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
779 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
780 mDownloadFinishReceiver
= new DownloadFinishReceiver();
781 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
783 Log_OC
.d(TAG
, "onResume() end");
788 protected void onPause() {
789 Log_OC
.e(TAG
, "onPause() start");
790 if (mSyncBroadcastReceiver
!= null
) {
791 unregisterReceiver(mSyncBroadcastReceiver
);
792 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
793 mSyncBroadcastReceiver
= null
;
795 if (mUploadFinishReceiver
!= null
) {
796 unregisterReceiver(mUploadFinishReceiver
);
797 mUploadFinishReceiver
= null
;
799 if (mDownloadFinishReceiver
!= null
) {
800 unregisterReceiver(mDownloadFinishReceiver
);
801 mDownloadFinishReceiver
= null
;
805 Log_OC
.d(TAG
, "onPause() end");
811 protected Dialog
onCreateDialog(int id
) {
812 Dialog dialog
= null
;
813 AlertDialog
.Builder builder
;
815 case DIALOG_SHORT_WAIT
: {
816 ProgressDialog working_dialog
= new ProgressDialog(this);
817 working_dialog
.setMessage(getResources().getString(
818 R
.string
.wait_a_moment
));
819 working_dialog
.setIndeterminate(true
);
820 working_dialog
.setCancelable(false
);
821 dialog
= working_dialog
;
824 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
827 String
[] allTheItems
= {getString(R
.string
.actionbar_upload_files
),
828 getString(R
.string
.actionbar_upload_from_apps
)};
830 builder
= new AlertDialog
.Builder(this);
831 builder
.setTitle(R
.string
.actionbar_upload
);
832 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
833 public void onClick(DialogInterface dialog
, int item
) {
836 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
837 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
838 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
840 // TODO create and handle new fragment
841 // LocalFileListFragment
843 } else if (item
== 1) {
844 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
845 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
846 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
847 ACTION_SELECT_CONTENT_FROM_APPS
);
851 dialog
= builder
.create();
854 case DIALOG_CERT_NOT_SAVED
: {
855 builder
= new AlertDialog
.Builder(this);
856 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
857 builder
.setCancelable(false
);
858 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
860 public void onClick(DialogInterface dialog
, int which
) {
866 dialog
= builder
.create();
878 * Translates a content URI of an image to a physical path
881 * @param uri The URI to resolve
882 * @return The path to the image or null if it could not be found
884 public String
getPath(Uri uri
) {
885 String
[] projection
= {MediaStore
.Images
.Media
.DATA
};
886 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
887 if (cursor
!= null
) {
888 int column_index
= cursor
889 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
890 cursor
.moveToFirst();
891 return cursor
.getString(column_index
);
897 * Pushes a directory to the drop down list
899 * @param directory to push
900 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
902 public void pushDirname(OCFile directory
) {
903 if (!directory
.isFolder()) {
904 throw new IllegalArgumentException("Only directories may be pushed!");
906 mDirectories
.insert(directory
.getFileName(), 0);
911 * Pops a directory name from the drop down list
913 * @return True, unless the stack is empty
915 public boolean popDirname() {
916 mDirectories
.remove(mDirectories
.getItem(0));
917 return !mDirectories
.isEmpty();
920 // Custom array adapter to override text colors
921 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
923 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
927 public View
getView(int position
, View convertView
, ViewGroup parent
) {
928 View v
= super.getView(position
, convertView
, parent
);
930 ((TextView
) v
).setTextColor(getResources().getColorStateList(
931 android
.R
.color
.white
));
933 fixRoot((TextView
) v
);
937 public View
getDropDownView(int position
, View convertView
,
939 View v
= super.getDropDownView(position
, convertView
, parent
);
941 ((TextView
) v
).setTextColor(getResources().getColorStateList(
942 android
.R
.color
.white
));
944 fixRoot((TextView
) v
);
948 private void fixRoot(TextView v
) {
949 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
950 v
.setText(R
.string
.default_display_name_for_root_folder
);
956 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
959 * {@link BroadcastReceiver} to enable syncing feedback in UI
962 public void onReceive(Context context
, Intent intent
) {
964 String event
= intent
.getAction();
965 Log_OC
.d(TAG
, "Received broadcast " + event
);
966 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
967 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
968 RemoteOperationResult synchResult
= (RemoteOperationResult
) intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
969 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
973 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
974 mSyncInProgress
= true
;
977 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
978 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
980 if (currentDir
== null
) {
981 // current folder was removed from the server
982 Toast
.makeText(FileDisplayActivity
.this,
983 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
989 if (currentFile
== null
&& !getFile().isFolder()) {
990 // currently selected file was removed in the server, and now we know it
991 cleanSecondFragment();
992 currentFile
= currentDir
;
995 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
996 OCFileListFragment fileListFragment
= getListOfFilesFragment();
997 if (fileListFragment
!= null
) {
998 fileListFragment
.listDirectory(currentDir
);
1001 setFile(currentFile
);
1004 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1006 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1008 /// TODO refactor and make common
1009 synchResult
!= null
&& !synchResult
.isSuccess() &&
1010 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1011 synchResult
.isIdPRedirection() ||
1012 (synchResult
.isException() && synchResult
.getException()
1013 instanceof AuthenticatorException
))) {
1015 OwnCloudClient client
= null
;
1017 OwnCloudAccount ocAccount
=
1018 new OwnCloudAccount(getAccount(), context
);
1019 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1020 removeClientFor(ocAccount
));
1021 // TODO get rid of these exceptions
1022 } catch (AccountNotFoundException e
) {
1023 e
.printStackTrace();
1024 } catch (AuthenticatorException e
) {
1025 e
.printStackTrace();
1026 } catch (OperationCanceledException e
) {
1027 e
.printStackTrace();
1028 } catch (IOException e
) {
1029 e
.printStackTrace();
1032 if (client
!= null
) {
1033 OwnCloudCredentials cred
= client
.getCredentials();
1035 AccountManager am
= AccountManager
.get(context
);
1036 if (cred
.authTokenExpires()) {
1037 am
.invalidateAuthToken(
1042 am
.clearPassword(getAccount());
1047 requestCredentialsUpdate();
1051 removeStickyBroadcast(intent
);
1052 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1053 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1055 setBackgroundText();
1059 if (synchResult
!= null
) {
1060 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1061 mLastSslUntrustedServerResult
= synchResult
;
1064 } catch (RuntimeException e
) {
1065 // avoid app crashes after changing the serial id of RemoteOperationResult
1066 // in owncloud library with broadcast notifications pending to process
1067 removeStickyBroadcast(intent
);
1073 * Show a text message on screen view for notifying user if content is
1074 * loading or folder is empty
1076 private void setBackgroundText() {
1077 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1078 if (ocFileListFragment
!= null
) {
1079 int message
= R
.string
.file_list_loading
;
1080 if (!mSyncInProgress
) {
1081 // In case file list is empty
1082 message
= R
.string
.file_list_empty
;
1084 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1086 Log_OC
.e(TAG
, "OCFileListFragment is null");
1091 * Once the file upload has finished -> update view
1093 private class UploadFinishReceiver
extends BroadcastReceiver
{
1095 * Once the file upload has finished -> update view
1097 * @author David A. Velasco
1098 * {@link BroadcastReceiver} to enable upload feedback in UI
1101 public void onReceive(Context context
, Intent intent
) {
1103 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1104 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1105 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1106 OCFile currentDir
= getCurrentDir();
1107 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1108 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1110 if (sameAccount
&& isDescendant
) {
1111 refreshListOfFilesFragment();
1114 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1115 boolean renamedInUpload
= getFile().getRemotePath().
1116 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1117 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1119 FileFragment details
= getSecondFragment();
1120 boolean detailFragmentIsShown
= (details
!= null
&&
1121 details
instanceof FileDetailFragment
);
1123 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1124 if (uploadWasFine
) {
1125 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1127 if (renamedInUpload
) {
1128 String newName
= (new File(uploadedRemotePath
)).getName();
1129 Toast msg
= Toast
.makeText(
1132 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1137 if (uploadWasFine
|| getFile().fileExists()) {
1138 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1140 cleanSecondFragment();
1143 // Force the preview if the file is an image or text file
1144 if (uploadWasFine
) {
1145 OCFile ocFile
= getFile();
1146 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1147 startImagePreview(getFile());
1148 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1149 startTextPreview(ocFile
);
1150 // TODO what about other kind of previews?
1155 if (intent
!= null
) {
1156 removeStickyBroadcast(intent
);
1166 * Class waiting for broadcast events from the {@link FileDownloader} service.
1168 * Updates the UI when a download is started or finished, provided that it is relevant for the
1171 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1173 public void onReceive(Context context
, Intent intent
) {
1175 boolean sameAccount
= isSameAccount(context
, intent
);
1176 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1177 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1179 if (sameAccount
&& isDescendant
) {
1180 refreshListOfFilesFragment();
1181 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1184 if (mWaitingToSend
!= null
) {
1185 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1186 if (mWaitingToSend
.isDown()) {
1187 sendDownloadedFile();
1192 if (intent
!= null
) {
1193 removeStickyBroadcast(intent
);
1198 private boolean isDescendant(String downloadedRemotePath
) {
1199 OCFile currentDir
= getCurrentDir();
1200 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1203 private boolean isSameAccount(Context context
, Intent intent
) {
1204 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1205 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1210 public void browseToRoot() {
1211 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1212 if (listOfFiles
!= null
) { // should never be null, indeed
1213 while (mDirectories
.getCount() > 1) {
1216 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1217 listOfFiles
.listDirectory(root
);
1218 setFile(listOfFiles
.getCurrentFile());
1219 startSyncFolderOperation(root
, false
);
1221 cleanSecondFragment();
1225 public void browseTo(OCFile folder
) {
1226 if (folder
== null
|| !folder
.isFolder()) {
1227 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1229 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1230 if (listOfFiles
!= null
) {
1231 setNavigationListWithFolder(folder
);
1232 listOfFiles
.listDirectory(folder
);
1233 setFile(listOfFiles
.getCurrentFile());
1234 startSyncFolderOperation(folder
, false
);
1236 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1238 cleanSecondFragment();
1245 * Updates action bar and second fragment, if in dual pane mode.
1248 public void onBrowsedDownTo(OCFile directory
) {
1249 pushDirname(directory
);
1250 cleanSecondFragment();
1253 startSyncFolderOperation(directory
, false
);
1258 * Shows the information of the {@link OCFile} received as a
1259 * parameter in the second fragment.
1261 * @param file {@link OCFile} whose details will be shown
1264 public void showDetails(OCFile file
) {
1265 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1266 setSecondFragment(detailFragment
);
1267 updateFragmentsVisibility(true
);
1268 updateNavigationElementsInActionBar(file
);
1276 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1277 ActionBar actionBar
= getSupportActionBar();
1278 if (chosenFile
== null
|| mDualPane
) {
1279 // only list of files - set for browsing through folders
1280 OCFile currentDir
= getCurrentDir();
1281 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1282 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1283 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1285 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1287 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1288 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1291 actionBar
.setDisplayHomeAsUpEnabled(true
);
1292 actionBar
.setDisplayShowTitleEnabled(true
);
1293 actionBar
.setTitle(chosenFile
.getFileName());
1294 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1300 protected ServiceConnection
newTransferenceServiceConnection() {
1301 return new ListServiceConnection();
1305 * Defines callbacks for service binding, passed to bindService()
1307 private class ListServiceConnection
implements ServiceConnection
{
1310 public void onServiceConnected(ComponentName component
, IBinder service
) {
1311 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1312 Log_OC
.d(TAG
, "Download service connected");
1313 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1314 if (mWaitingToPreview
!= null
)
1315 if (getStorageManager() != null
) {
1316 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1317 if (!mWaitingToPreview
.isDown()) {
1318 requestForDownload();
1322 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1323 Log_OC
.d(TAG
, "Upload service connected");
1324 mUploaderBinder
= (FileUploaderBinder
) service
;
1328 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1329 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1330 if (listOfFiles
!= null
) {
1331 listOfFiles
.listDirectory();
1333 FileFragment secondFragment
= getSecondFragment();
1334 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1335 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1336 detailFragment
.listenForTransferProgress();
1337 detailFragment
.updateFileDetails(false
, false
);
1342 public void onServiceDisconnected(ComponentName component
) {
1343 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1344 Log_OC
.d(TAG
, "Download service disconnected");
1345 mDownloaderBinder
= null
;
1346 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1347 Log_OC
.d(TAG
, "Upload service disconnected");
1348 mUploaderBinder
= null
;
1357 * Launch an intent to request the PIN code to the user before letting him use the app
1359 private void requestPinCode() {
1360 boolean pinStart
= false
;
1361 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1362 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1364 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1365 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1372 public void onSavedCertificate() {
1373 startSyncFolderOperation(getCurrentDir(), false
);
1378 public void onFailedSavingCertificate() {
1379 showDialog(DIALOG_CERT_NOT_SAVED
);
1383 public void onCancelCertificate() {
1388 * Updates the view associated to the activity after the finish of some operation over files
1389 * in the current account.
1391 * @param operation Removal operation performed.
1392 * @param result Result of the removal.
1395 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1396 super.onRemoteOperationFinish(operation
, result
);
1398 if (operation
instanceof RemoveFileOperation
) {
1399 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1401 } else if (operation
instanceof RenameFileOperation
) {
1402 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1404 } else if (operation
instanceof SynchronizeFileOperation
) {
1405 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1407 } else if (operation
instanceof CreateFolderOperation
) {
1408 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1410 } else if (operation
instanceof CreateShareOperation
) {
1411 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1413 } else if (operation
instanceof UnshareLinkOperation
) {
1414 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1416 } else if (operation
instanceof MoveFileOperation
) {
1417 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1423 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1424 if (result
.isSuccess()) {
1425 refreshShowDetails();
1426 refreshListOfFilesFragment();
1431 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1432 if (result
.isSuccess()) {
1433 refreshShowDetails();
1434 refreshListOfFilesFragment();
1436 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1437 cleanSecondFragment();
1438 refreshListOfFilesFragment();
1442 private void refreshShowDetails() {
1443 FileFragment details
= getSecondFragment();
1444 if (details
!= null
) {
1445 OCFile file
= details
.getFile();
1447 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1448 if (details
instanceof PreviewMediaFragment
) {
1449 // Refresh OCFile of the fragment
1450 ((PreviewMediaFragment
) details
).updateFile(file
);
1451 } else if (details
instanceof PreviewTextFragment
) {
1452 // Refresh OCFile of the fragment
1453 ((PreviewTextFragment
) details
).updateFile(file
);
1457 invalidateOptionsMenu();
1462 * Updates the view associated to the activity after the finish of an operation trying to remove a
1465 * @param operation Removal operation performed.
1466 * @param result Result of the removal.
1468 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1469 dismissLoadingDialog();
1471 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1475 if (result
.isSuccess()) {
1476 OCFile removedFile
= operation
.getFile();
1477 FileFragment second
= getSecondFragment();
1478 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1479 if (second
instanceof PreviewMediaFragment
) {
1480 ((PreviewMediaFragment
) second
).stopPreview(true
);
1482 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1483 cleanSecondFragment();
1485 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1486 refreshListOfFilesFragment();
1488 invalidateOptionsMenu();
1490 if (result
.isSslRecoverableException()) {
1491 mLastSslUntrustedServerResult
= result
;
1492 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1499 * Updates the view associated to the activity after the finish of an operation trying to move a
1502 * @param operation Move operation performed.
1503 * @param result Result of the move operation.
1505 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1506 if (result
.isSuccess()) {
1507 dismissLoadingDialog();
1508 refreshListOfFilesFragment();
1510 dismissLoadingDialog();
1512 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1513 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1517 } catch (NotFoundException e
) {
1518 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1525 * Updates the view associated to the activity after the finish of an operation trying to rename a
1528 * @param operation Renaming operation performed.
1529 * @param result Result of the renaming.
1531 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1532 dismissLoadingDialog();
1533 OCFile renamedFile
= operation
.getFile();
1534 if (result
.isSuccess()) {
1535 FileFragment details
= getSecondFragment();
1536 if (details
!= null
) {
1537 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile())) {
1538 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1539 showDetails(renamedFile
);
1541 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1542 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1543 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1544 int position
= ((PreviewMediaFragment
) details
).getPosition();
1545 startMediaPreview(renamedFile
, position
, true
);
1547 getFileOperationsHelper().openFile(renamedFile
);
1549 } else if (details
instanceof PreviewTextFragment
&& renamedFile
.equals(details
.getFile())) {
1550 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1551 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1552 startTextPreview(renamedFile
);
1554 getFileOperationsHelper().openFile(renamedFile
);
1559 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1560 refreshListOfFilesFragment();
1564 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1568 if (result
.isSslRecoverableException()) {
1569 mLastSslUntrustedServerResult
= result
;
1570 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1575 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1576 dismissLoadingDialog();
1577 OCFile syncedFile
= operation
.getLocalFile();
1578 if (!result
.isSuccess()) {
1579 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1580 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1581 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1582 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1588 if (operation
.transferWasRequested()) {
1589 onTransferStateChanged(syncedFile
, true
, true
);
1592 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1600 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1602 * @param operation Creation operation performed.
1603 * @param result Result of the creation.
1605 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1606 if (result
.isSuccess()) {
1607 dismissLoadingDialog();
1608 refreshListOfFilesFragment();
1610 dismissLoadingDialog();
1612 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1613 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1617 } catch (NotFoundException e
) {
1618 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1628 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1629 refreshListOfFilesFragment();
1630 FileFragment details
= getSecondFragment();
1631 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile())) {
1632 if (downloading
|| uploading
) {
1633 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1635 if (!file
.fileExists()) {
1636 cleanSecondFragment();
1638 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1646 private void requestForDownload() {
1647 Account account
= getAccount();
1648 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1649 Intent i
= new Intent(this, FileDownloader
.class);
1650 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1651 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1657 private OCFile
getCurrentDir() {
1658 OCFile file
= getFile();
1660 if (file
.isFolder()) {
1662 } else if (getStorageManager() != null
) {
1663 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1664 return getStorageManager().getFileByPath(parentPath
);
1670 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1671 long currentSyncTime
= System
.currentTimeMillis();
1673 mSyncInProgress
= true
;
1675 // perform folder synchronization
1676 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation(folder
,
1679 getFileOperationsHelper().isSharedSupported(),
1681 getStorageManager(),
1683 getApplicationContext()
1685 synchFolderOp
.execute(getAccount(), this, null
, null
);
1687 setSupportProgressBarIndeterminateVisibility(true
);
1689 setBackgroundText();
1693 * Show untrusted cert dialog
1695 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1696 // Show a dialog with the certificate info
1697 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
) result
.getException());
1698 FragmentManager fm
= getSupportFragmentManager();
1699 FragmentTransaction ft
= fm
.beginTransaction();
1700 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1703 private void requestForDownload(OCFile file
) {
1704 Account account
= getAccount();
1705 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1706 Intent i
= new Intent(this, FileDownloader
.class);
1707 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1708 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1713 private void sendDownloadedFile() {
1714 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1715 mWaitingToSend
= null
;
1720 * Requests the download of the received {@link OCFile} , updates the UI
1721 * to monitor the download progress and prepares the activity to send the file
1722 * when the download finishes.
1724 * @param file {@link OCFile} to download and preview.
1726 public void startDownloadForSending(OCFile file
) {
1727 mWaitingToSend
= file
;
1728 requestForDownload(mWaitingToSend
);
1729 boolean hasSecondFragment
= (getSecondFragment() != null
);
1730 updateFragmentsVisibility(hasSecondFragment
);
1734 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1736 * @param file Image {@link OCFile} to show.
1738 public void startImagePreview(OCFile file
) {
1739 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1740 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1741 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1742 startActivity(showDetailsIntent
);
1746 * Stars the preview of an already down media {@link OCFile}.
1748 * @param file Media {@link OCFile} to preview.
1749 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1750 * @param autoplay When 'true', the playback will start without user interactions.
1752 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1753 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1754 setSecondFragment(mediaFragment
);
1755 updateFragmentsVisibility(true
);
1756 updateNavigationElementsInActionBar(file
);
1761 * Stars the preview of a text file {@link OCFile}.
1763 * @param file Text {@link OCFile} to preview.
1765 public void startTextPreview(OCFile file
) {
1766 Bundle args
= new Bundle();
1767 args
.putParcelable(EXTRA_FILE
, file
);
1768 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1769 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(), PreviewTextFragment
.class.getName(), args
);
1770 setSecondFragment(textPreviewFragment
);
1771 updateFragmentsVisibility(true
);
1772 updateNavigationElementsInActionBar(file
);
1777 * Requests the download of the received {@link OCFile} , updates the UI
1778 * to monitor the download progress and prepares the activity to preview
1779 * or open the file when the download finishes.
1781 * @param file {@link OCFile} to download and preview.
1783 public void startDownloadForPreview(OCFile file
) {
1784 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1785 setSecondFragment(detailFragment
);
1786 mWaitingToPreview
= file
;
1787 requestForDownload();
1788 updateFragmentsVisibility(true
);
1789 updateNavigationElementsInActionBar(file
);
1794 public void cancelTransference(OCFile file
) {
1795 getFileOperationsHelper().cancelTransference(file
);
1796 if (mWaitingToPreview
!= null
&&
1797 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1798 mWaitingToPreview
= null
;
1800 if (mWaitingToSend
!= null
&&
1801 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1802 mWaitingToSend
= null
;
1804 onTransferStateChanged(file
, false
, false
);
1808 public void onRefresh(boolean ignoreETag
) {
1809 refreshList(ignoreETag
);
1813 public void onRefresh() {
1817 private void refreshList(boolean ignoreETag
) {
1818 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1819 if (listOfFiles
!= null
) {
1820 OCFile folder
= listOfFiles
.getCurrentFile();
1821 if (folder
!= null
) {
1822 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1823 listDirectory(mFile);*/
1824 startSyncFolderOperation(folder
, ignoreETag
);
1829 private void sortByDate(boolean ascending
) {
1830 getListOfFilesFragment().sortByDate(ascending
);
1833 private void sortBySize(boolean ascending
) {
1834 getListOfFilesFragment().sortBySize(ascending
);
1837 private void sortByName(boolean ascending
) {
1838 getListOfFilesFragment().sortByName(ascending
);