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();
310 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
311 if (getAccount() == null
) {
312 Log_OC
.wtf(TAG
, "\t account is NULL");
314 if (getFile() == null
) {
315 Log_OC
.wtf(TAG
, "\t file is NULL");
320 private Fragment
chooseInitialSecondFragment(OCFile file
) {
321 Fragment secondFragment
= null
;
322 if (file
!= null
&& !file
.isFolder()) {
323 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
324 && file
.getLastSyncDateForProperties() > 0 // temporal fix
326 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
327 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
328 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
331 secondFragment
= new FileDetailFragment(file
, getAccount());
334 return secondFragment
;
339 * Replaces the second fragment managed by the activity with the received as
342 * Assumes never will be more than two fragments managed at the same time.
344 * @param fragment New second Fragment to set.
346 private void setSecondFragment(Fragment fragment
) {
347 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
348 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
349 transaction
.commit();
353 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
355 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
356 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
358 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
359 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
362 } else if (existsSecondFragment
) {
363 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
364 mLeftFragmentContainer
.setVisibility(View
.GONE
);
366 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
371 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
372 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
374 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
375 mRightFragmentContainer
.setVisibility(View
.GONE
);
381 private OCFileListFragment
getListOfFilesFragment() {
382 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
383 if (listOfFiles
!= null
) {
384 return (OCFileListFragment
) listOfFiles
;
386 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
390 public FileFragment
getSecondFragment() {
391 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
392 if (second
!= null
) {
393 return (FileFragment
) second
;
398 protected void cleanSecondFragment() {
399 Fragment second
= getSecondFragment();
400 if (second
!= null
) {
401 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
405 updateFragmentsVisibility(false
);
406 updateNavigationElementsInActionBar(null
);
409 protected void refreshListOfFilesFragment() {
410 OCFileListFragment fileListFragment
= getListOfFilesFragment();
411 if (fileListFragment
!= null
) {
412 fileListFragment
.listDirectory();
416 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
417 FileFragment secondFragment
= getSecondFragment();
418 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
419 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
420 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
421 OCFile fileInFragment
= detailsFragment
.getFile();
422 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
423 // the user browsed to other file ; forget the automatic preview
424 mWaitingToPreview
= null
;
426 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
427 // grant that the right panel updates the progress bar
428 detailsFragment
.listenForTransferProgress();
429 detailsFragment
.updateFileDetails(true
, false
);
431 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
432 // update the right panel
433 boolean detailsFragmentChanged
= false
;
436 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
437 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
438 startMediaPreview(mWaitingToPreview
, 0, true
);
439 detailsFragmentChanged
= true
;
440 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
441 startTextPreview(mWaitingToPreview
);
442 detailsFragmentChanged
= true
;
444 getFileOperationsHelper().openFile(mWaitingToPreview
);
447 mWaitingToPreview
= null
;
449 if (!detailsFragmentChanged
) {
450 detailsFragment
.updateFileDetails(false
, (success
));
457 public boolean onPrepareOptionsMenu(Menu menu
) {
458 if (BuildConfig
.DEBUG
) {
459 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
461 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
463 return super.onPrepareOptionsMenu(menu
);
467 public boolean onCreateOptionsMenu(Menu menu
) {
468 MenuInflater inflater
= getSherlock().getMenuInflater();
469 inflater
.inflate(R
.menu
.main_menu
, menu
);
474 public boolean onOptionsItemSelected(MenuItem item
) {
475 boolean retval
= true
;
476 switch (item
.getItemId()) {
477 case R
.id
.action_create_dir
: {
478 CreateFolderDialogFragment dialog
=
479 CreateFolderDialogFragment
.newInstance(getCurrentDir());
480 dialog
.show(getSupportFragmentManager(), "createdirdialog");
483 case R
.id
.action_sort
: {
484 SharedPreferences appPreferences
= PreferenceManager
485 .getDefaultSharedPreferences(this);
487 // Read sorting order, default to sort by name ascending
488 Integer sortOrder
= appPreferences
489 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
491 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
492 builder
.setTitle(R
.string
.actionbar_sort_title
)
493 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
494 public void onClick(DialogInterface dialog
, int which
) {
504 // TODO re-enable when server-side folder size calculation is available
506 // sortBySize(false);
514 builder
.create().show();
517 case R
.id
.action_sync_account
: {
518 startSynchronization();
521 case R
.id
.action_upload
: {
522 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
525 case R
.id
.action_settings
: {
526 Intent settingsIntent
= new Intent(this, Preferences
.class);
527 startActivity(settingsIntent
);
530 case R
.id
.action_logger
: {
531 Intent loggerIntent
= new Intent(getApplicationContext(), LogHistoryActivity
.class);
532 startActivity(loggerIntent
);
535 case android
.R
.id
.home
: {
536 FileFragment second
= getSecondFragment();
537 OCFile currentDir
= getCurrentDir();
538 if ((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
539 (second
!= null
&& second
.getFile() != null
)) {
546 retval
= super.onOptionsItemSelected(item
);
551 private void startSynchronization() {
552 Log_OC
.e(TAG
, "Got to start sync");
553 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
554 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
555 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
556 Bundle bundle
= new Bundle();
557 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
558 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
559 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
560 ContentResolver
.requestSync(
562 MainApp
.getAuthority(), bundle
);
564 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
565 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
566 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
567 builder
.setExpedited(true
);
568 builder
.setManual(true
);
570 SyncRequest request
= builder
.build();
571 ContentResolver
.requestSync(request
);
577 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
578 if (itemPosition
!= 0) {
579 String targetPath
= "";
580 for (int i
= itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
581 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
583 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
584 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
585 if (targetFolder
!= null
) {
586 browseTo(targetFolder
);
589 // the next operation triggers a new call to this method, but it's necessary to
590 // ensure that the name exposed in the action bar is the current directory when the
591 // user selected it in the navigation list
592 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
593 getSupportActionBar().setSelectedNavigationItem(0);
599 * Called, when the user selected something for uploading
601 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
602 super.onActivityResult(requestCode
, resultCode
, data
);
604 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
605 requestSimpleUpload(data
, resultCode
);
607 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
608 requestMultipleUpload(data
, resultCode
);
610 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
611 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)) {
613 final Intent fData
= data
;
614 final int fResultCode
= resultCode
;
615 getHandler().postDelayed(
619 requestMoveOperation(fData
, fResultCode
);
622 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
627 private void requestMultipleUpload(Intent data
, int resultCode
) {
628 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
629 if (filePaths
!= null
) {
630 String
[] remotePaths
= new String
[filePaths
.length
];
631 String remotePathBase
= "";
632 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
633 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
635 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
636 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
637 for (int j
= 0; j
< remotePaths
.length
; j
++) {
638 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
641 Intent i
= new Intent(this, FileUploader
.class);
642 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
643 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
644 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
645 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
646 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
647 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
651 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
652 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
659 private void requestSimpleUpload(Intent data
, int resultCode
) {
660 String filepath
= null
;
662 Uri selectedImageUri
= data
.getData();
664 String filemanagerstring
= selectedImageUri
.getPath();
665 String selectedImagePath
= getPath(selectedImageUri
);
667 if (selectedImagePath
!= null
)
668 filepath
= selectedImagePath
;
670 filepath
= filemanagerstring
;
672 } catch (Exception e
) {
673 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
677 if (filepath
== null
) {
678 Log_OC
.e(TAG
, "Couldnt resolve path to file");
679 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
685 Intent i
= new Intent(this, FileUploader
.class);
686 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
688 String remotepath
= new String();
689 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
690 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
692 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
693 remotepath
+= OCFile
.PATH_SEPARATOR
;
694 remotepath
+= new File(filepath
).getName();
696 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
697 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
698 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
699 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
700 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
705 * Request the operation for moving the file/folder from one path to another
707 * @param data Intent received
708 * @param resultCode Result code received
710 private void requestMoveOperation(Intent data
, int resultCode
) {
711 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
712 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
713 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
717 public void onBackPressed() {
718 OCFileListFragment listOfFiles
= getListOfFilesFragment();
719 if (mDualPane
|| getSecondFragment() == null
) {
720 if (listOfFiles
!= null
) { // should never be null, indeed
721 if (mDirectories
.getCount() <= 1) {
725 int levelsUp
= listOfFiles
.onBrowseUp();
726 for (int i
= 0; i
< levelsUp
&& mDirectories
.getCount() > 1; i
++) {
731 if (listOfFiles
!= null
) { // should never be null, indeed
732 setFile(listOfFiles
.getCurrentFile());
734 cleanSecondFragment();
739 protected void onSaveInstanceState(Bundle outState
) {
740 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
741 Log_OC
.e(TAG
, "onSaveInstanceState() start");
742 super.onSaveInstanceState(outState
);
743 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
744 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
745 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
746 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
748 Log_OC
.d(TAG
, "onSaveInstanceState() end");
753 protected void onResume() {
755 Log_OC
.e(TAG
, "onResume() start");
757 // refresh list of files
758 refreshListOfFilesFragment();
760 // Listen for sync messages
761 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
762 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
763 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
764 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
765 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
766 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
767 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
768 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
770 // Listen for upload messages
771 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
772 mUploadFinishReceiver
= new UploadFinishReceiver();
773 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
775 // Listen for download messages
776 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
777 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
778 mDownloadFinishReceiver
= new DownloadFinishReceiver();
779 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
781 Log_OC
.d(TAG
, "onResume() end");
786 protected void onPause() {
787 Log_OC
.e(TAG
, "onPause() start");
788 if (mSyncBroadcastReceiver
!= null
) {
789 unregisterReceiver(mSyncBroadcastReceiver
);
790 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
791 mSyncBroadcastReceiver
= null
;
793 if (mUploadFinishReceiver
!= null
) {
794 unregisterReceiver(mUploadFinishReceiver
);
795 mUploadFinishReceiver
= null
;
797 if (mDownloadFinishReceiver
!= null
) {
798 unregisterReceiver(mDownloadFinishReceiver
);
799 mDownloadFinishReceiver
= null
;
803 Log_OC
.d(TAG
, "onPause() end");
809 protected Dialog
onCreateDialog(int id
) {
810 Dialog dialog
= null
;
811 AlertDialog
.Builder builder
;
813 case DIALOG_SHORT_WAIT
: {
814 ProgressDialog working_dialog
= new ProgressDialog(this);
815 working_dialog
.setMessage(getResources().getString(
816 R
.string
.wait_a_moment
));
817 working_dialog
.setIndeterminate(true
);
818 working_dialog
.setCancelable(false
);
819 dialog
= working_dialog
;
822 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
825 String
[] allTheItems
= {getString(R
.string
.actionbar_upload_files
),
826 getString(R
.string
.actionbar_upload_from_apps
)};
828 builder
= new AlertDialog
.Builder(this);
829 builder
.setTitle(R
.string
.actionbar_upload
);
830 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
831 public void onClick(DialogInterface dialog
, int item
) {
834 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
835 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
836 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
838 // TODO create and handle new fragment
839 // LocalFileListFragment
841 } else if (item
== 1) {
842 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
843 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
844 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
845 ACTION_SELECT_CONTENT_FROM_APPS
);
849 dialog
= builder
.create();
852 case DIALOG_CERT_NOT_SAVED
: {
853 builder
= new AlertDialog
.Builder(this);
854 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
855 builder
.setCancelable(false
);
856 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
858 public void onClick(DialogInterface dialog
, int which
) {
864 dialog
= builder
.create();
876 * Translates a content URI of an image to a physical path
879 * @param uri The URI to resolve
880 * @return The path to the image or null if it could not be found
882 public String
getPath(Uri uri
) {
883 String
[] projection
= {MediaStore
.Images
.Media
.DATA
};
884 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
885 if (cursor
!= null
) {
886 int column_index
= cursor
887 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
888 cursor
.moveToFirst();
889 return cursor
.getString(column_index
);
895 * Pushes a directory to the drop down list
897 * @param directory to push
898 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
900 public void pushDirname(OCFile directory
) {
901 if (!directory
.isFolder()) {
902 throw new IllegalArgumentException("Only directories may be pushed!");
904 mDirectories
.insert(directory
.getFileName(), 0);
909 * Pops a directory name from the drop down list
911 * @return True, unless the stack is empty
913 public boolean popDirname() {
914 mDirectories
.remove(mDirectories
.getItem(0));
915 return !mDirectories
.isEmpty();
918 // Custom array adapter to override text colors
919 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
921 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
925 public View
getView(int position
, View convertView
, ViewGroup parent
) {
926 View v
= super.getView(position
, convertView
, parent
);
928 ((TextView
) v
).setTextColor(getResources().getColorStateList(
929 android
.R
.color
.white
));
931 fixRoot((TextView
) v
);
935 public View
getDropDownView(int position
, View convertView
,
937 View v
= super.getDropDownView(position
, convertView
, parent
);
939 ((TextView
) v
).setTextColor(getResources().getColorStateList(
940 android
.R
.color
.white
));
942 fixRoot((TextView
) v
);
946 private void fixRoot(TextView v
) {
947 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
948 v
.setText(R
.string
.default_display_name_for_root_folder
);
954 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
957 * {@link BroadcastReceiver} to enable syncing feedback in UI
960 public void onReceive(Context context
, Intent intent
) {
962 String event
= intent
.getAction();
963 Log_OC
.d(TAG
, "Received broadcast " + event
);
964 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
965 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
966 RemoteOperationResult synchResult
= (RemoteOperationResult
) intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
967 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
971 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
972 mSyncInProgress
= true
;
975 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
976 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
978 if (currentDir
== null
) {
979 // current folder was removed from the server
980 Toast
.makeText(FileDisplayActivity
.this,
981 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
987 if (currentFile
== null
&& !getFile().isFolder()) {
988 // currently selected file was removed in the server, and now we know it
989 cleanSecondFragment();
990 currentFile
= currentDir
;
993 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
994 OCFileListFragment fileListFragment
= getListOfFilesFragment();
995 if (fileListFragment
!= null
) {
996 fileListFragment
.listDirectory(currentDir
);
999 setFile(currentFile
);
1002 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1004 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1006 /// TODO refactor and make common
1007 synchResult
!= null
&& !synchResult
.isSuccess() &&
1008 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1009 synchResult
.isIdPRedirection() ||
1010 (synchResult
.isException() && synchResult
.getException()
1011 instanceof AuthenticatorException
))) {
1013 OwnCloudClient client
= null
;
1015 OwnCloudAccount ocAccount
=
1016 new OwnCloudAccount(getAccount(), context
);
1017 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1018 removeClientFor(ocAccount
));
1019 // TODO get rid of these exceptions
1020 } catch (AccountNotFoundException e
) {
1021 e
.printStackTrace();
1022 } catch (AuthenticatorException e
) {
1023 e
.printStackTrace();
1024 } catch (OperationCanceledException e
) {
1025 e
.printStackTrace();
1026 } catch (IOException e
) {
1027 e
.printStackTrace();
1030 if (client
!= null
) {
1031 OwnCloudCredentials cred
= client
.getCredentials();
1033 AccountManager am
= AccountManager
.get(context
);
1034 if (cred
.authTokenExpires()) {
1035 am
.invalidateAuthToken(
1040 am
.clearPassword(getAccount());
1045 requestCredentialsUpdate();
1049 removeStickyBroadcast(intent
);
1050 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1051 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1053 setBackgroundText();
1057 if (synchResult
!= null
) {
1058 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1059 mLastSslUntrustedServerResult
= synchResult
;
1062 } catch (RuntimeException e
) {
1063 // avoid app crashes after changing the serial id of RemoteOperationResult
1064 // in owncloud library with broadcast notifications pending to process
1065 removeStickyBroadcast(intent
);
1071 * Show a text message on screen view for notifying user if content is
1072 * loading or folder is empty
1074 private void setBackgroundText() {
1075 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1076 if (ocFileListFragment
!= null
) {
1077 int message
= R
.string
.file_list_loading
;
1078 if (!mSyncInProgress
) {
1079 // In case file list is empty
1080 message
= R
.string
.file_list_empty
;
1082 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1084 Log_OC
.e(TAG
, "OCFileListFragment is null");
1089 * Once the file upload has finished -> update view
1091 private class UploadFinishReceiver
extends BroadcastReceiver
{
1093 * Once the file upload has finished -> update view
1095 * @author David A. Velasco
1096 * {@link BroadcastReceiver} to enable upload feedback in UI
1099 public void onReceive(Context context
, Intent intent
) {
1101 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1102 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1103 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1104 OCFile currentDir
= getCurrentDir();
1105 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1106 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1108 if (sameAccount
&& isDescendant
) {
1109 refreshListOfFilesFragment();
1112 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1113 boolean renamedInUpload
= getFile().getRemotePath().
1114 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1115 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1117 FileFragment details
= getSecondFragment();
1118 boolean detailFragmentIsShown
= (details
!= null
&&
1119 details
instanceof FileDetailFragment
);
1121 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1122 if (uploadWasFine
) {
1123 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1125 if (renamedInUpload
) {
1126 String newName
= (new File(uploadedRemotePath
)).getName();
1127 Toast msg
= Toast
.makeText(
1130 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1135 if (uploadWasFine
|| getFile().fileExists()) {
1136 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1138 cleanSecondFragment();
1141 // Force the preview if the file is an image or text file
1142 if (uploadWasFine
) {
1143 OCFile ocFile
= getFile();
1144 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1145 startImagePreview(getFile());
1146 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1147 startTextPreview(ocFile
);
1148 // TODO what about other kind of previews?
1153 if (intent
!= null
) {
1154 removeStickyBroadcast(intent
);
1164 * Class waiting for broadcast events from the {@link FileDownloader} service.
1166 * Updates the UI when a download is started or finished, provided that it is relevant for the
1169 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1171 public void onReceive(Context context
, Intent intent
) {
1173 boolean sameAccount
= isSameAccount(context
, intent
);
1174 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1175 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1177 if (sameAccount
&& isDescendant
) {
1178 refreshListOfFilesFragment();
1179 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1182 if (mWaitingToSend
!= null
) {
1183 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1184 if (mWaitingToSend
.isDown()) {
1185 sendDownloadedFile();
1190 if (intent
!= null
) {
1191 removeStickyBroadcast(intent
);
1196 private boolean isDescendant(String downloadedRemotePath
) {
1197 OCFile currentDir
= getCurrentDir();
1198 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1201 private boolean isSameAccount(Context context
, Intent intent
) {
1202 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1203 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1208 public void browseToRoot() {
1209 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1210 if (listOfFiles
!= null
) { // should never be null, indeed
1211 while (mDirectories
.getCount() > 1) {
1214 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1215 listOfFiles
.listDirectory(root
);
1216 setFile(listOfFiles
.getCurrentFile());
1217 startSyncFolderOperation(root
, false
);
1219 cleanSecondFragment();
1223 public void browseTo(OCFile folder
) {
1224 if (folder
== null
|| !folder
.isFolder()) {
1225 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1227 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1228 if (listOfFiles
!= null
) {
1229 setNavigationListWithFolder(folder
);
1230 listOfFiles
.listDirectory(folder
);
1231 setFile(listOfFiles
.getCurrentFile());
1232 startSyncFolderOperation(folder
, false
);
1234 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1236 cleanSecondFragment();
1243 * Updates action bar and second fragment, if in dual pane mode.
1246 public void onBrowsedDownTo(OCFile directory
) {
1247 pushDirname(directory
);
1248 cleanSecondFragment();
1251 startSyncFolderOperation(directory
, false
);
1256 * Shows the information of the {@link OCFile} received as a
1257 * parameter in the second fragment.
1259 * @param file {@link OCFile} whose details will be shown
1262 public void showDetails(OCFile file
) {
1263 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1264 setSecondFragment(detailFragment
);
1265 updateFragmentsVisibility(true
);
1266 updateNavigationElementsInActionBar(file
);
1274 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1275 ActionBar actionBar
= getSupportActionBar();
1276 if (chosenFile
== null
|| mDualPane
) {
1277 // only list of files - set for browsing through folders
1278 OCFile currentDir
= getCurrentDir();
1279 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1280 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1281 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1283 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1285 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1286 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1289 actionBar
.setDisplayHomeAsUpEnabled(true
);
1290 actionBar
.setDisplayShowTitleEnabled(true
);
1291 actionBar
.setTitle(chosenFile
.getFileName());
1292 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1298 protected ServiceConnection
newTransferenceServiceConnection() {
1299 return new ListServiceConnection();
1303 * Defines callbacks for service binding, passed to bindService()
1305 private class ListServiceConnection
implements ServiceConnection
{
1308 public void onServiceConnected(ComponentName component
, IBinder service
) {
1309 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1310 Log_OC
.d(TAG
, "Download service connected");
1311 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1312 if (mWaitingToPreview
!= null
)
1313 if (getStorageManager() != null
) {
1314 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1315 if (!mWaitingToPreview
.isDown()) {
1316 requestForDownload();
1320 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1321 Log_OC
.d(TAG
, "Upload service connected");
1322 mUploaderBinder
= (FileUploaderBinder
) service
;
1326 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1327 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1328 if (listOfFiles
!= null
) {
1329 listOfFiles
.listDirectory();
1331 FileFragment secondFragment
= getSecondFragment();
1332 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1333 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1334 detailFragment
.listenForTransferProgress();
1335 detailFragment
.updateFileDetails(false
, false
);
1340 public void onServiceDisconnected(ComponentName component
) {
1341 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1342 Log_OC
.d(TAG
, "Download service disconnected");
1343 mDownloaderBinder
= null
;
1344 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1345 Log_OC
.d(TAG
, "Upload service disconnected");
1346 mUploaderBinder
= null
;
1355 * Launch an intent to request the PIN code to the user before letting him use the app
1357 private void requestPinCode() {
1358 boolean pinStart
= false
;
1359 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1360 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1362 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1363 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1370 public void onSavedCertificate() {
1371 startSyncFolderOperation(getCurrentDir(), false
);
1376 public void onFailedSavingCertificate() {
1377 showDialog(DIALOG_CERT_NOT_SAVED
);
1381 public void onCancelCertificate() {
1386 * Updates the view associated to the activity after the finish of some operation over files
1387 * in the current account.
1389 * @param operation Removal operation performed.
1390 * @param result Result of the removal.
1393 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1394 super.onRemoteOperationFinish(operation
, result
);
1396 if (operation
instanceof RemoveFileOperation
) {
1397 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1399 } else if (operation
instanceof RenameFileOperation
) {
1400 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1402 } else if (operation
instanceof SynchronizeFileOperation
) {
1403 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1405 } else if (operation
instanceof CreateFolderOperation
) {
1406 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1408 } else if (operation
instanceof CreateShareOperation
) {
1409 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1411 } else if (operation
instanceof UnshareLinkOperation
) {
1412 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1414 } else if (operation
instanceof MoveFileOperation
) {
1415 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1421 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1422 if (result
.isSuccess()) {
1423 refreshShowDetails();
1424 refreshListOfFilesFragment();
1429 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1430 if (result
.isSuccess()) {
1431 refreshShowDetails();
1432 refreshListOfFilesFragment();
1434 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1435 cleanSecondFragment();
1436 refreshListOfFilesFragment();
1440 private void refreshShowDetails() {
1441 FileFragment details
= getSecondFragment();
1442 if (details
!= null
) {
1443 OCFile file
= details
.getFile();
1445 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1446 if (details
instanceof PreviewMediaFragment
) {
1447 // Refresh OCFile of the fragment
1448 ((PreviewMediaFragment
) details
).updateFile(file
);
1453 invalidateOptionsMenu();
1458 * Updates the view associated to the activity after the finish of an operation trying to remove a
1461 * @param operation Removal operation performed.
1462 * @param result Result of the removal.
1464 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1465 dismissLoadingDialog();
1467 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1471 if (result
.isSuccess()) {
1472 OCFile removedFile
= operation
.getFile();
1473 FileFragment second
= getSecondFragment();
1474 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1475 if (second
instanceof PreviewMediaFragment
) {
1476 ((PreviewMediaFragment
) second
).stopPreview(true
);
1478 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1479 cleanSecondFragment();
1481 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1482 refreshListOfFilesFragment();
1484 invalidateOptionsMenu();
1486 if (result
.isSslRecoverableException()) {
1487 mLastSslUntrustedServerResult
= result
;
1488 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1495 * Updates the view associated to the activity after the finish of an operation trying to move a
1498 * @param operation Move operation performed.
1499 * @param result Result of the move operation.
1501 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1502 if (result
.isSuccess()) {
1503 dismissLoadingDialog();
1504 refreshListOfFilesFragment();
1506 dismissLoadingDialog();
1508 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1509 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1513 } catch (NotFoundException e
) {
1514 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1521 * Updates the view associated to the activity after the finish of an operation trying to rename a
1524 * @param operation Renaming operation performed.
1525 * @param result Result of the renaming.
1527 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1528 dismissLoadingDialog();
1529 OCFile renamedFile
= operation
.getFile();
1530 if (result
.isSuccess()) {
1531 FileFragment details
= getSecondFragment();
1532 if (details
!= null
) {
1533 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile())) {
1534 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1535 showDetails(renamedFile
);
1537 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1538 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1539 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1540 int position
= ((PreviewMediaFragment
) details
).getPosition();
1541 startMediaPreview(renamedFile
, position
, true
);
1543 getFileOperationsHelper().openFile(renamedFile
);
1545 } else if (details
instanceof PreviewTextFragment
&& renamedFile
.equals(details
.getFile())) {
1546 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1547 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1548 startTextPreview(renamedFile
);
1550 getFileOperationsHelper().openFile(renamedFile
);
1555 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1556 refreshListOfFilesFragment();
1560 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1564 if (result
.isSslRecoverableException()) {
1565 mLastSslUntrustedServerResult
= result
;
1566 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1571 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1572 dismissLoadingDialog();
1573 OCFile syncedFile
= operation
.getLocalFile();
1574 if (!result
.isSuccess()) {
1575 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1576 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1577 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1578 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1584 if (operation
.transferWasRequested()) {
1585 onTransferStateChanged(syncedFile
, true
, true
);
1588 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1596 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1598 * @param operation Creation operation performed.
1599 * @param result Result of the creation.
1601 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1602 if (result
.isSuccess()) {
1603 dismissLoadingDialog();
1604 refreshListOfFilesFragment();
1606 dismissLoadingDialog();
1608 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1609 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1613 } catch (NotFoundException e
) {
1614 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1624 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1625 refreshListOfFilesFragment();
1626 FileFragment details
= getSecondFragment();
1627 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile())) {
1628 if (downloading
|| uploading
) {
1629 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1631 if (!file
.fileExists()) {
1632 cleanSecondFragment();
1634 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1642 private void requestForDownload() {
1643 Account account
= getAccount();
1644 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1645 Intent i
= new Intent(this, FileDownloader
.class);
1646 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1647 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1653 private OCFile
getCurrentDir() {
1654 OCFile file
= getFile();
1656 if (file
.isFolder()) {
1658 } else if (getStorageManager() != null
) {
1659 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1660 return getStorageManager().getFileByPath(parentPath
);
1666 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1667 long currentSyncTime
= System
.currentTimeMillis();
1669 mSyncInProgress
= true
;
1671 // perform folder synchronization
1672 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation(folder
,
1675 getFileOperationsHelper().isSharedSupported(),
1677 getStorageManager(),
1679 getApplicationContext()
1681 synchFolderOp
.execute(getAccount(), this, null
, null
);
1683 setSupportProgressBarIndeterminateVisibility(true
);
1685 setBackgroundText();
1689 * Show untrusted cert dialog
1691 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1692 // Show a dialog with the certificate info
1693 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
) result
.getException());
1694 FragmentManager fm
= getSupportFragmentManager();
1695 FragmentTransaction ft
= fm
.beginTransaction();
1696 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1699 private void requestForDownload(OCFile file
) {
1700 Account account
= getAccount();
1701 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1702 Intent i
= new Intent(this, FileDownloader
.class);
1703 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1704 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1709 private void sendDownloadedFile() {
1710 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1711 mWaitingToSend
= null
;
1716 * Requests the download of the received {@link OCFile} , updates the UI
1717 * to monitor the download progress and prepares the activity to send the file
1718 * when the download finishes.
1720 * @param file {@link OCFile} to download and preview.
1722 public void startDownloadForSending(OCFile file
) {
1723 mWaitingToSend
= file
;
1724 requestForDownload(mWaitingToSend
);
1725 boolean hasSecondFragment
= (getSecondFragment() != null
);
1726 updateFragmentsVisibility(hasSecondFragment
);
1730 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1732 * @param file Image {@link OCFile} to show.
1734 public void startImagePreview(OCFile file
) {
1735 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1736 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1737 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1738 startActivity(showDetailsIntent
);
1742 * Stars the preview of an already down media {@link OCFile}.
1744 * @param file Media {@link OCFile} to preview.
1745 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1746 * @param autoplay When 'true', the playback will start without user interactions.
1748 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1749 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1750 setSecondFragment(mediaFragment
);
1751 updateFragmentsVisibility(true
);
1752 updateNavigationElementsInActionBar(file
);
1757 * Stars the preview of a text file {@link OCFile}.
1759 * @param file Text {@link OCFile} to preview.
1761 public void startTextPreview(OCFile file
) {
1762 Bundle args
= new Bundle();
1763 args
.putParcelable(EXTRA_FILE
, file
);
1764 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1765 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(), PreviewTextFragment
.class.getName(), args
);
1766 setSecondFragment(textPreviewFragment
);
1767 updateFragmentsVisibility(true
);
1768 updateNavigationElementsInActionBar(file
);
1773 * Requests the download of the received {@link OCFile} , updates the UI
1774 * to monitor the download progress and prepares the activity to preview
1775 * or open the file when the download finishes.
1777 * @param file {@link OCFile} to download and preview.
1779 public void startDownloadForPreview(OCFile file
) {
1780 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1781 setSecondFragment(detailFragment
);
1782 mWaitingToPreview
= file
;
1783 requestForDownload();
1784 updateFragmentsVisibility(true
);
1785 updateNavigationElementsInActionBar(file
);
1790 public void cancelTransference(OCFile file
) {
1791 getFileOperationsHelper().cancelTransference(file
);
1792 if (mWaitingToPreview
!= null
&&
1793 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1794 mWaitingToPreview
= null
;
1796 if (mWaitingToSend
!= null
&&
1797 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1798 mWaitingToSend
= null
;
1800 onTransferStateChanged(file
, false
, false
);
1804 public void onRefresh(boolean ignoreETag
) {
1805 refreshList(ignoreETag
);
1809 public void onRefresh() {
1813 private void refreshList(boolean ignoreETag
) {
1814 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1815 if (listOfFiles
!= null
) {
1816 OCFile folder
= listOfFiles
.getCurrentFile();
1817 if (folder
!= null
) {
1818 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1819 listDirectory(mFile);*/
1820 startSyncFolderOperation(folder
, ignoreETag
);
1825 private void sortByDate(boolean ascending
) {
1826 getListOfFilesFragment().sortByDate(ascending
);
1829 private void sortBySize(boolean ascending
) {
1830 getListOfFilesFragment().sortBySize(ascending
);
1833 private void sortByName(boolean ascending
) {
1834 getListOfFilesFragment().sortByName(ascending
);