1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
26 import android
.accounts
.Account
;
27 import android
.accounts
.AccountManager
;
28 import android
.accounts
.AuthenticatorException
;
29 import android
.accounts
.OperationCanceledException
;
30 import android
.app
.AlertDialog
;
31 import android
.app
.Dialog
;
32 import android
.app
.ProgressDialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ComponentName
;
35 import android
.content
.ContentResolver
;
36 import android
.content
.Context
;
37 import android
.content
.DialogInterface
;
38 import android
.content
.Intent
;
39 import android
.content
.IntentFilter
;
40 import android
.content
.ServiceConnection
;
41 import android
.content
.SharedPreferences
;
42 import android
.content
.SyncRequest
;
43 import android
.content
.res
.Resources
.NotFoundException
;
44 import android
.database
.Cursor
;
45 import android
.net
.Uri
;
46 import android
.os
.Bundle
;
47 import android
.os
.IBinder
;
48 import android
.preference
.PreferenceManager
;
49 import android
.provider
.MediaStore
;
50 import android
.support
.v4
.app
.Fragment
;
51 import android
.support
.v4
.app
.FragmentManager
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.support
.v4
.widget
.SwipeRefreshLayout
;
54 import android
.util
.Log
;
55 import android
.view
.View
;
56 import android
.view
.ViewGroup
;
57 import android
.widget
.ArrayAdapter
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.ActionBar
;
62 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
63 import com
.actionbarsherlock
.view
.Menu
;
64 import com
.actionbarsherlock
.view
.MenuInflater
;
65 import com
.actionbarsherlock
.view
.MenuItem
;
66 import com
.actionbarsherlock
.view
.Window
;
67 import com
.owncloud
.android
.MainApp
;
68 import com
.owncloud
.android
.R
;
69 import com
.owncloud
.android
.datamodel
.OCFile
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
78 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
79 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
84 import com
.owncloud
.android
.operations
.CreateShareOperation
;
85 import com
.owncloud
.android
.operations
.MoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RenameFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
89 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
90 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
91 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
92 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
93 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
94 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
96 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
97 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
104 import com
.owncloud
.android
.utils
.DisplayUtils
;
105 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
106 import com
.owncloud
.android
.utils
.Log_OC
;
110 * Displays, what files the user has available in his ownCloud.
112 * @author Bartek Przybylski
113 * @author David A. Velasco
116 public class FileDisplayActivity
extends HookActivity
implements
117 FileFragment
.ContainerActivity
, OnNavigationListener
,
118 OnSslUntrustedCertListener
, SwipeRefreshLayout
.OnRefreshListener
{
120 private ArrayAdapter
<String
> mDirectories
;
122 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
123 private UploadFinishReceiver mUploadFinishReceiver
;
124 private DownloadFinishReceiver mDownloadFinishReceiver
;
125 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
127 private boolean mDualPane
;
128 private View mLeftFragmentContainer
;
129 private View mRightFragmentContainer
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final int DIALOG_SHORT_WAIT
= 0;
136 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
137 private static final int DIALOG_CERT_NOT_SAVED
= 2;
139 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
141 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
142 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
143 public static final int ACTION_MOVE_FILES
= 3;
145 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
147 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
148 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
150 private OCFile mWaitingToPreview
;
152 private boolean mSyncInProgress
= false
;
154 private String DIALOG_UNTRUSTED_CERT
;
156 private OCFile mWaitingToSend
;
159 protected void onCreate(Bundle savedInstanceState
) {
160 Log_OC
.d(TAG
, "onCreate() start");
161 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
163 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
165 // PIN CODE request ; best location is to decide, let's try this first
166 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
168 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
172 /// grant that FileObserverService is watching favourite files
173 if (savedInstanceState
== null
) {
174 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
175 startService(initObserversIntent
);
178 /// Load of saved instance state
179 if(savedInstanceState
!= null
) {
180 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
181 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
182 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
185 mWaitingToPreview
= null
;
186 mSyncInProgress
= false
;
187 mWaitingToSend
= null
;
192 // Inflate and set the layout view
193 setContentView(R
.layout
.files
);
194 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
195 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
196 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
197 if (savedInstanceState
== null
) {
198 createMinFragments();
202 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
203 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
204 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
208 Log_OC
.d(TAG
, "onCreate() end");
212 protected void onStart() {
214 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
218 protected void onDestroy() {
223 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
226 protected void onAccountSet(boolean stateWasRecovered
) {
227 super.onAccountSet(stateWasRecovered
);
228 if (getAccount() != null
) {
229 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
230 OCFile file
= getFile();
231 // get parent from path
232 String parentPath
= "";
234 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
235 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
236 // get parent from path
237 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
238 if (getStorageManager().getFileByPath(parentPath
) == null
)
239 file
= null
; // not able to know the directory where the file is uploading
241 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
245 // fall back to root folder
246 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
249 setNavigationListWithFolder(file
);
251 if (!stateWasRecovered
) {
252 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
253 initFragmentsWithFile();
254 if (file
.isFolder()) {
255 startSyncFolderOperation(file
);
259 updateFragmentsVisibility(!file
.isFolder());
260 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
266 private void setNavigationListWithFolder(OCFile file
) {
267 mDirectories
.clear();
268 OCFile fileIt
= file
;
270 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
271 if (fileIt
.isFolder()) {
272 mDirectories
.add(fileIt
.getFileName());
274 // get parent from path
275 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
276 fileIt
= getStorageManager().getFileByPath(parentPath
);
278 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
282 private void createMinFragments() {
283 OCFileListFragment listOfFiles
= new OCFileListFragment();
284 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
285 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
286 transaction
.commit();
289 private void initFragmentsWithFile() {
290 if (getAccount() != null
&& getFile() != null
) {
292 OCFileListFragment listOfFiles
= getListOfFilesFragment();
293 if (listOfFiles
!= null
) {
294 listOfFiles
.listDirectory(getCurrentDir());
296 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
300 OCFile file
= getFile();
301 Fragment secondFragment
= chooseInitialSecondFragment(file
);
302 if (secondFragment
!= null
) {
303 setSecondFragment(secondFragment
);
304 updateFragmentsVisibility(true
);
305 updateNavigationElementsInActionBar(file
);
308 cleanSecondFragment();
312 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
313 if (getAccount() == null
) {
314 Log
.wtf(TAG
, "\t account is NULL");
316 if (getFile() == null
) {
317 Log
.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
);
333 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
;
443 getFileOperationsHelper().openFile(mWaitingToPreview
);
446 mWaitingToPreview
= null
;
448 if (!detailsFragmentChanged
) {
449 detailsFragment
.updateFileDetails(false
, (success
));
456 public boolean onCreateOptionsMenu(Menu menu
) {
457 MenuInflater inflater
= getSherlock().getMenuInflater();
458 inflater
.inflate(R
.menu
.main_menu
, menu
);
463 public boolean onOptionsItemSelected(MenuItem item
) {
464 boolean retval
= true
;
465 switch (item
.getItemId()) {
466 case R
.id
.action_create_dir
: {
467 CreateFolderDialogFragment dialog
=
468 CreateFolderDialogFragment
.newInstance(getCurrentDir());
469 dialog
.show(getSupportFragmentManager(), "createdirdialog");
472 case R
.id
.action_sync_account
: {
473 startSynchronization();
476 case R
.id
.action_upload
: {
477 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
480 case R
.id
.action_settings
: {
481 Intent settingsIntent
= new Intent(this, Preferences
.class);
482 startActivity(settingsIntent
);
485 case android
.R
.id
.home
: {
486 FileFragment second
= getSecondFragment();
487 OCFile currentDir
= getCurrentDir();
488 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
489 (second
!= null
&& second
.getFile() != null
)) {
495 case R
.id
.action_sort
: {
496 SharedPreferences appPreferences
= PreferenceManager
497 .getDefaultSharedPreferences(this);
499 // Read sorting order, default to sort by name ascending
500 Integer sortOrder
= appPreferences
501 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
503 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
504 builder
.setTitle(R
.string
.actionbar_sort_title
)
505 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
506 public void onClick(DialogInterface dialog
, int which
) {
516 // TODO re-enable when server-side folder size calculation is available
518 // sortBySize(false);
526 builder
.create().show();
530 retval
= super.onOptionsItemSelected(item
);
535 private void startSynchronization() {
536 Log_OC
.e(TAG
, "Got to start sync");
537 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
538 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
539 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
540 Bundle bundle
= new Bundle();
541 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
542 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
543 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
544 ContentResolver
.requestSync(
546 MainApp
.getAuthority(), bundle
);
548 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
549 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
550 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
551 builder
.setExpedited(true
);
552 builder
.setManual(true
);
554 SyncRequest request
= builder
.build();
555 ContentResolver
.requestSync(request
);
561 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
562 if (itemPosition
!= 0) {
563 String targetPath
= "";
564 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
565 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
567 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
568 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
569 if (targetFolder
!= null
) {
570 browseTo(targetFolder
);
573 // the next operation triggers a new call to this method, but it's necessary to
574 // ensure that the name exposed in the action bar is the current directory when the
575 // user selected it in the navigation list
576 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
577 getSupportActionBar().setSelectedNavigationItem(0);
583 * Called, when the user selected something for uploading
585 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
586 super.onActivityResult(requestCode
, resultCode
, data
);
588 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
589 requestSimpleUpload(data
, resultCode
);
591 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
592 requestMultipleUpload(data
, resultCode
);
594 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
595 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
597 final Intent fData
= data
;
598 final int fResultCode
= resultCode
;
599 getHandler().postDelayed(
603 requestMoveOperation(fData
, fResultCode
);
606 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
611 private void requestMultipleUpload(Intent data
, int resultCode
) {
612 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
613 if (filePaths
!= null
) {
614 String
[] remotePaths
= new String
[filePaths
.length
];
615 String remotePathBase
= "";
616 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
617 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
619 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
620 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
621 for (int j
= 0; j
< remotePaths
.length
; j
++) {
622 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
625 Intent i
= new Intent(this, FileUploader
.class);
626 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
627 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
628 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
629 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
630 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
631 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
635 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
636 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
643 private void requestSimpleUpload(Intent data
, int resultCode
) {
644 String filepath
= null
;
646 Uri selectedImageUri
= data
.getData();
648 String filemanagerstring
= selectedImageUri
.getPath();
649 String selectedImagePath
= getPath(selectedImageUri
);
651 if (selectedImagePath
!= null
)
652 filepath
= selectedImagePath
;
654 filepath
= filemanagerstring
;
656 } catch (Exception e
) {
657 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
661 if (filepath
== null
) {
662 Log_OC
.e(TAG
, "Couldnt resolve path to file");
663 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
669 Intent i
= new Intent(this, FileUploader
.class);
670 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
672 String remotepath
= new String();
673 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
674 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
676 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
677 remotepath
+= OCFile
.PATH_SEPARATOR
;
678 remotepath
+= new File(filepath
).getName();
680 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
681 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
682 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
683 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
684 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
689 * Request the operation for moving the file/folder from one path to another
691 * @param data Intent received
692 * @param resultCode Result code received
694 private void requestMoveOperation(Intent data
, int resultCode
) {
695 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
696 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
697 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
701 public void onBackPressed() {
702 OCFileListFragment listOfFiles
= getListOfFilesFragment();
703 if (mDualPane
|| getSecondFragment() == null
) {
704 if (listOfFiles
!= null
) { // should never be null, indeed
705 if (mDirectories
.getCount() <= 1) {
709 int levelsUp
= listOfFiles
.onBrowseUp();
710 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
715 if (listOfFiles
!= null
) { // should never be null, indeed
716 setFile(listOfFiles
.getCurrentFile());
718 cleanSecondFragment();
723 protected void onSaveInstanceState(Bundle outState
) {
724 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
725 Log_OC
.e(TAG
, "onSaveInstanceState() start");
726 super.onSaveInstanceState(outState
);
727 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
728 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
729 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
730 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
732 Log_OC
.d(TAG
, "onSaveInstanceState() end");
738 protected void onResume() {
740 Log_OC
.e(TAG
, "onResume() start");
742 // refresh list of files
743 refreshListOfFilesFragment();
745 // Listen for sync messages
746 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
747 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
748 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
749 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
750 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
751 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
752 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
753 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
755 // Listen for upload messages
756 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
757 mUploadFinishReceiver
= new UploadFinishReceiver();
758 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
760 // Listen for download messages
761 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
762 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
763 mDownloadFinishReceiver
= new DownloadFinishReceiver();
764 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
766 Log_OC
.d(TAG
, "onResume() end");
771 protected void onPause() {
772 Log_OC
.e(TAG
, "onPause() start");
773 if (mSyncBroadcastReceiver
!= null
) {
774 unregisterReceiver(mSyncBroadcastReceiver
);
775 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
776 mSyncBroadcastReceiver
= null
;
778 if (mUploadFinishReceiver
!= null
) {
779 unregisterReceiver(mUploadFinishReceiver
);
780 mUploadFinishReceiver
= null
;
782 if (mDownloadFinishReceiver
!= null
) {
783 unregisterReceiver(mDownloadFinishReceiver
);
784 mDownloadFinishReceiver
= null
;
788 Log_OC
.d(TAG
, "onPause() end");
794 protected Dialog
onCreateDialog(int id
) {
795 Dialog dialog
= null
;
796 AlertDialog
.Builder builder
;
798 case DIALOG_SHORT_WAIT
: {
799 ProgressDialog working_dialog
= new ProgressDialog(this);
800 working_dialog
.setMessage(getResources().getString(
801 R
.string
.wait_a_moment
));
802 working_dialog
.setIndeterminate(true
);
803 working_dialog
.setCancelable(false
);
804 dialog
= working_dialog
;
807 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
810 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
811 getString(R
.string
.actionbar_upload_from_apps
) };
813 builder
= new AlertDialog
.Builder(this);
814 builder
.setTitle(R
.string
.actionbar_upload
);
815 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
816 public void onClick(DialogInterface dialog
, int item
) {
819 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
820 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
821 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
823 // TODO create and handle new fragment
824 // LocalFileListFragment
826 } else if (item
== 1) {
827 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
828 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
829 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
830 ACTION_SELECT_CONTENT_FROM_APPS
);
834 dialog
= builder
.create();
837 case DIALOG_CERT_NOT_SAVED
: {
838 builder
= new AlertDialog
.Builder(this);
839 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
840 builder
.setCancelable(false
);
841 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
843 public void onClick(DialogInterface dialog
, int which
) {
847 dialog
= builder
.create();
859 * Translates a content URI of an image to a physical path
861 * @param uri The URI to resolve
862 * @return The path to the image or null if it could not be found
864 public String
getPath(Uri uri
) {
865 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
866 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
867 if (cursor
!= null
) {
868 int column_index
= cursor
869 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
870 cursor
.moveToFirst();
871 return cursor
.getString(column_index
);
877 * Pushes a directory to the drop down list
878 * @param directory to push
879 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
881 public void pushDirname(OCFile directory
) {
882 if(!directory
.isFolder()){
883 throw new IllegalArgumentException("Only directories may be pushed!");
885 mDirectories
.insert(directory
.getFileName(), 0);
890 * Pops a directory name from the drop down list
891 * @return True, unless the stack is empty
893 public boolean popDirname() {
894 mDirectories
.remove(mDirectories
.getItem(0));
895 return !mDirectories
.isEmpty();
898 // Custom array adapter to override text colors
899 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
901 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
905 public View
getView(int position
, View convertView
, ViewGroup parent
) {
906 View v
= super.getView(position
, convertView
, parent
);
908 ((TextView
) v
).setTextColor(getResources().getColorStateList(
909 android
.R
.color
.white
));
911 fixRoot((TextView
) v
);
915 public View
getDropDownView(int position
, View convertView
,
917 View v
= super.getDropDownView(position
, convertView
, parent
);
919 ((TextView
) v
).setTextColor(getResources().getColorStateList(
920 android
.R
.color
.white
));
922 fixRoot((TextView
) v
);
926 private void fixRoot(TextView v
) {
927 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
928 v
.setText(R
.string
.default_display_name_for_root_folder
);
934 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
937 * {@link BroadcastReceiver} to enable syncing feedback in UI
940 public void onReceive(Context context
, Intent intent
) {
942 String event
= intent
.getAction();
943 Log_OC
.d(TAG
, "Received broadcast " + event
);
944 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
945 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
946 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
947 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
951 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
952 mSyncInProgress
= true
;
955 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
956 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
958 if (currentDir
== null
) {
959 // current folder was removed from the server
960 Toast
.makeText( FileDisplayActivity
.this,
961 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
967 if (currentFile
== null
&& !getFile().isFolder()) {
968 // currently selected file was removed in the server, and now we know it
969 cleanSecondFragment();
970 currentFile
= currentDir
;
973 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
974 OCFileListFragment fileListFragment
= getListOfFilesFragment();
975 if (fileListFragment
!= null
) {
976 fileListFragment
.listDirectory(currentDir
);
979 setFile(currentFile
);
982 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
984 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
986 /// TODO refactor and make common
987 synchResult
!= null
&& !synchResult
.isSuccess() &&
988 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
989 synchResult
.isIdPRedirection() ||
990 (synchResult
.isException() && synchResult
.getException()
991 instanceof AuthenticatorException
))) {
993 OwnCloudClient client
= null
;
995 OwnCloudAccount ocAccount
=
996 new OwnCloudAccount(getAccount(), context
);
997 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
998 removeClientFor(ocAccount
));
999 // TODO get rid of these exceptions
1000 } catch (AccountNotFoundException e
) {
1001 e
.printStackTrace();
1002 } catch (AuthenticatorException e
) {
1003 e
.printStackTrace();
1004 } catch (OperationCanceledException e
) {
1005 e
.printStackTrace();
1006 } catch (IOException e
) {
1007 e
.printStackTrace();
1010 if (client
!= null
) {
1011 OwnCloudCredentials cred
= client
.getCredentials();
1013 AccountManager am
= AccountManager
.get(context
);
1014 if (cred
.authTokenExpires()) {
1015 am
.invalidateAuthToken(
1020 am
.clearPassword(getAccount());
1025 requestCredentialsUpdate();
1029 removeStickyBroadcast(intent
);
1030 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1031 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1033 setBackgroundText();
1037 if (synchResult
!= null
) {
1038 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1039 mLastSslUntrustedServerResult
= synchResult
;
1042 } catch (RuntimeException e
) {
1043 // avoid app crashes after changing the serial id of RemoteOperationResult
1044 // in owncloud library with broadcast notifications pending to process
1045 removeStickyBroadcast(intent
);
1051 * Show a text message on screen view for notifying user if content is
1052 * loading or folder is empty
1054 private void setBackgroundText() {
1055 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1056 if (ocFileListFragment
!= null
) {
1057 int message
= R
.string
.file_list_loading
;
1058 if (!mSyncInProgress
) {
1059 // In case file list is empty
1060 message
= R
.string
.file_list_empty
;
1062 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1064 Log
.e(TAG
, "OCFileListFragment is null");
1069 * Once the file upload has finished -> update view
1071 private class UploadFinishReceiver
extends BroadcastReceiver
{
1073 * Once the file upload has finished -> update view
1074 * @author David A. Velasco
1075 * {@link BroadcastReceiver} to enable upload feedback in UI
1078 public void onReceive(Context context
, Intent intent
) {
1080 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1081 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1082 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1083 OCFile currentDir
= getCurrentDir();
1084 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1085 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1087 if (sameAccount
&& isDescendant
) {
1088 refreshListOfFilesFragment();
1091 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1092 boolean renamedInUpload
= getFile().getRemotePath().
1093 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1094 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1096 FileFragment details
= getSecondFragment();
1097 boolean detailFragmentIsShown
= (details
!= null
&&
1098 details
instanceof FileDetailFragment
);
1100 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1101 if (uploadWasFine
) {
1102 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1104 if (renamedInUpload
) {
1105 String newName
= (new File(uploadedRemotePath
)).getName();
1106 Toast msg
= Toast
.makeText(
1109 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1114 if (uploadWasFine
|| getFile().fileExists()) {
1115 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1117 cleanSecondFragment();
1120 // Force the preview if the file is an image
1121 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1122 startImagePreview(getFile());
1123 } // TODO what about other kind of previews?
1127 if (intent
!= null
) {
1128 removeStickyBroadcast(intent
);
1138 * Class waiting for broadcast events from the {@link FielDownloader} service.
1140 * Updates the UI when a download is started or finished, provided that it is relevant for the
1143 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1145 public void onReceive(Context context
, Intent intent
) {
1147 boolean sameAccount
= isSameAccount(context
, intent
);
1148 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1149 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1151 if (sameAccount
&& isDescendant
) {
1152 refreshListOfFilesFragment();
1153 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1156 if (mWaitingToSend
!= null
) {
1157 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1158 if (mWaitingToSend
.isDown()) {
1159 sendDownloadedFile();
1164 if (intent
!= null
) {
1165 removeStickyBroadcast(intent
);
1170 private boolean isDescendant(String downloadedRemotePath
) {
1171 OCFile currentDir
= getCurrentDir();
1172 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1175 private boolean isSameAccount(Context context
, Intent intent
) {
1176 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1177 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1182 public void browseToRoot() {
1183 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1184 if (listOfFiles
!= null
) { // should never be null, indeed
1185 while (mDirectories
.getCount() > 1) {
1188 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1189 listOfFiles
.listDirectory(root
);
1190 setFile(listOfFiles
.getCurrentFile());
1191 startSyncFolderOperation(root
);
1193 cleanSecondFragment();
1197 public void browseTo(OCFile folder
) {
1198 if (folder
== null
|| !folder
.isFolder()) {
1199 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1201 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1202 if (listOfFiles
!= null
) {
1203 setNavigationListWithFolder(folder
);
1204 listOfFiles
.listDirectory(folder
);
1205 setFile(listOfFiles
.getCurrentFile());
1206 startSyncFolderOperation(folder
);
1208 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1210 cleanSecondFragment();
1217 * Updates action bar and second fragment, if in dual pane mode.
1220 public void onBrowsedDownTo(OCFile directory
) {
1221 pushDirname(directory
);
1222 cleanSecondFragment();
1225 startSyncFolderOperation(directory
);
1230 * Shows the information of the {@link OCFile} received as a
1231 * parameter in the second fragment.
1233 * @param file {@link OCFile} whose details will be shown
1236 public void showDetails(OCFile file
) {
1237 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1238 setSecondFragment(detailFragment
);
1239 updateFragmentsVisibility(true
);
1240 updateNavigationElementsInActionBar(file
);
1248 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1249 ActionBar actionBar
= getSupportActionBar();
1250 if (chosenFile
== null
|| mDualPane
) {
1251 // only list of files - set for browsing through folders
1252 OCFile currentDir
= getCurrentDir();
1253 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1254 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1255 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1257 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1259 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1260 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1263 actionBar
.setDisplayHomeAsUpEnabled(true
);
1264 actionBar
.setDisplayShowTitleEnabled(true
);
1265 actionBar
.setTitle(chosenFile
.getFileName());
1266 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1272 protected ServiceConnection
newTransferenceServiceConnection() {
1273 return new ListServiceConnection();
1276 /** Defines callbacks for service binding, passed to bindService() */
1277 private class ListServiceConnection
implements ServiceConnection
{
1280 public void onServiceConnected(ComponentName component
, IBinder service
) {
1281 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1282 Log_OC
.d(TAG
, "Download service connected");
1283 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1284 if (mWaitingToPreview
!= null
)
1285 if (getStorageManager() != null
) {
1286 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1287 if (!mWaitingToPreview
.isDown()) {
1288 requestForDownload();
1292 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1293 Log_OC
.d(TAG
, "Upload service connected");
1294 mUploaderBinder
= (FileUploaderBinder
) service
;
1298 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1299 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1300 if (listOfFiles
!= null
) {
1301 listOfFiles
.listDirectory();
1303 FileFragment secondFragment
= getSecondFragment();
1304 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1305 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1306 detailFragment
.listenForTransferProgress();
1307 detailFragment
.updateFileDetails(false
, false
);
1312 public void onServiceDisconnected(ComponentName component
) {
1313 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1314 Log_OC
.d(TAG
, "Download service disconnected");
1315 mDownloaderBinder
= null
;
1316 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1317 Log_OC
.d(TAG
, "Upload service disconnected");
1318 mUploaderBinder
= null
;
1326 * Launch an intent to request the PIN code to the user before letting him use the app
1328 private void requestPinCode() {
1329 boolean pinStart
= false
;
1330 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1331 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1333 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1334 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1341 public void onSavedCertificate() {
1342 startSyncFolderOperation(getCurrentDir());
1347 public void onFailedSavingCertificate() {
1348 showDialog(DIALOG_CERT_NOT_SAVED
);
1352 public void onCancelCertificate() {
1357 * Updates the view associated to the activity after the finish of some operation over files
1358 * in the current account.
1360 * @param operation Removal operation performed.
1361 * @param result Result of the removal.
1364 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1365 super.onRemoteOperationFinish(operation
, result
);
1367 if (operation
instanceof RemoveFileOperation
) {
1368 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1370 } else if (operation
instanceof RenameFileOperation
) {
1371 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1373 } else if (operation
instanceof SynchronizeFileOperation
) {
1374 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1376 } else if (operation
instanceof CreateFolderOperation
) {
1377 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1379 } else if (operation
instanceof CreateShareOperation
) {
1380 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1382 } else if (operation
instanceof UnshareLinkOperation
) {
1383 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1385 } else if (operation
instanceof MoveFileOperation
) {
1386 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1392 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1393 if (result
.isSuccess()) {
1394 refreshShowDetails();
1395 refreshListOfFilesFragment();
1400 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1401 if (result
.isSuccess()) {
1402 refreshShowDetails();
1403 refreshListOfFilesFragment();
1405 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1406 cleanSecondFragment();
1407 refreshListOfFilesFragment();
1411 private void refreshShowDetails() {
1412 FileFragment details
= getSecondFragment();
1413 if (details
!= null
) {
1414 OCFile file
= details
.getFile();
1416 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1417 if (details
instanceof PreviewMediaFragment
) {
1418 // Refresh OCFile of the fragment
1419 ((PreviewMediaFragment
) details
).updateFile(file
);
1424 invalidateOptionsMenu();
1429 * Updates the view associated to the activity after the finish of an operation trying to remove a
1432 * @param operation Removal operation performed.
1433 * @param result Result of the removal.
1435 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1436 dismissLoadingDialog();
1438 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1442 if (result
.isSuccess()) {
1443 OCFile removedFile
= operation
.getFile();
1444 FileFragment second
= getSecondFragment();
1445 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1446 if (second
instanceof PreviewMediaFragment
) {
1447 ((PreviewMediaFragment
)second
).stopPreview(true
);
1449 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1450 cleanSecondFragment();
1452 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1453 refreshListOfFilesFragment();
1455 invalidateOptionsMenu();
1457 if (result
.isSslRecoverableException()) {
1458 mLastSslUntrustedServerResult
= result
;
1459 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1466 * Updates the view associated to the activity after the finish of an operation trying to move a
1469 * @param operation Move operation performed.
1470 * @param result Result of the move operation.
1472 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1473 if (result
.isSuccess()) {
1474 dismissLoadingDialog();
1475 refreshListOfFilesFragment();
1477 dismissLoadingDialog();
1479 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1480 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1484 } catch (NotFoundException e
) {
1485 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1492 * Updates the view associated to the activity after the finish of an operation trying to rename a
1495 * @param operation Renaming operation performed.
1496 * @param result Result of the renaming.
1498 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1499 dismissLoadingDialog();
1500 OCFile renamedFile
= operation
.getFile();
1501 if (result
.isSuccess()) {
1502 FileFragment details
= getSecondFragment();
1503 if (details
!= null
) {
1504 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1505 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1506 showDetails(renamedFile
);
1508 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1509 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1510 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1511 int position
= ((PreviewMediaFragment
)details
).getPosition();
1512 startMediaPreview(renamedFile
, position
, true
);
1514 getFileOperationsHelper().openFile(renamedFile
);
1519 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1520 refreshListOfFilesFragment();
1524 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1528 if (result
.isSslRecoverableException()) {
1529 mLastSslUntrustedServerResult
= result
;
1530 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1535 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1536 dismissLoadingDialog();
1537 OCFile syncedFile
= operation
.getLocalFile();
1538 if (!result
.isSuccess()) {
1539 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1540 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1541 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1542 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1548 if (operation
.transferWasRequested()) {
1549 onTransferStateChanged(syncedFile
, true
, true
);
1552 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1560 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1562 * @param operation Creation operation performed.
1563 * @param result Result of the creation.
1565 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1566 if (result
.isSuccess()) {
1567 dismissLoadingDialog();
1568 refreshListOfFilesFragment();
1570 dismissLoadingDialog();
1572 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1573 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1577 } catch (NotFoundException e
) {
1578 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1588 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1589 refreshListOfFilesFragment();
1590 FileFragment details
= getSecondFragment();
1591 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1592 if (downloading
|| uploading
) {
1593 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1595 if (!file
.fileExists()) {
1596 cleanSecondFragment();
1598 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1606 private void requestForDownload() {
1607 Account account
= getAccount();
1608 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1609 Intent i
= new Intent(this, FileDownloader
.class);
1610 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1611 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1617 private OCFile
getCurrentDir() {
1618 OCFile file
= getFile();
1620 if (file
.isFolder()) {
1622 } else if (getStorageManager() != null
) {
1623 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1624 return getStorageManager().getFileByPath(parentPath
);
1630 public void startSyncFolderOperation(OCFile folder
) {
1631 long currentSyncTime
= System
.currentTimeMillis();
1633 mSyncInProgress
= true
;
1635 // perform folder synchronization
1636 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1639 getFileOperationsHelper().isSharedSupported(),
1640 getStorageManager(),
1642 getApplicationContext()
1644 synchFolderOp
.execute(getAccount(), this, null
, null
);
1646 setSupportProgressBarIndeterminateVisibility(true
);
1648 setBackgroundText();
1652 * Show untrusted cert dialog
1654 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1655 // Show a dialog with the certificate info
1656 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1657 FragmentManager fm
= getSupportFragmentManager();
1658 FragmentTransaction ft
= fm
.beginTransaction();
1659 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1662 private void requestForDownload(OCFile file
) {
1663 Account account
= getAccount();
1664 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1665 Intent i
= new Intent(this, FileDownloader
.class);
1666 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1667 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1672 private void sendDownloadedFile(){
1673 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1674 mWaitingToSend
= null
;
1679 * Requests the download of the received {@link OCFile} , updates the UI
1680 * to monitor the download progress and prepares the activity to send the file
1681 * when the download finishes.
1683 * @param file {@link OCFile} to download and preview.
1685 public void startDownloadForSending(OCFile file
) {
1686 mWaitingToSend
= file
;
1687 requestForDownload(mWaitingToSend
);
1688 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1689 updateFragmentsVisibility(hasSecondFragment
);
1693 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1695 * @param file Image {@link OCFile} to show.
1697 public void startImagePreview(OCFile file
) {
1698 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1699 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1700 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1701 startActivity(showDetailsIntent
);
1706 * Stars the preview of an already down media {@link OCFile}.
1708 * @param file Media {@link OCFile} to preview.
1709 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1710 * @param autoplay When 'true', the playback will start without user interactions.
1712 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1713 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1714 setSecondFragment(mediaFragment
);
1715 updateFragmentsVisibility(true
);
1716 updateNavigationElementsInActionBar(file
);
1721 * Requests the download of the received {@link OCFile} , updates the UI
1722 * to monitor the download progress and prepares the activity to preview
1723 * or open the file when the download finishes.
1725 * @param file {@link OCFile} to download and preview.
1727 public void startDownloadForPreview(OCFile file
) {
1728 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1729 setSecondFragment(detailFragment
);
1730 mWaitingToPreview
= file
;
1731 requestForDownload();
1732 updateFragmentsVisibility(true
);
1733 updateNavigationElementsInActionBar(file
);
1738 public void cancelTransference(OCFile file
) {
1739 getFileOperationsHelper().cancelTransference(file
);
1740 if (mWaitingToPreview
!= null
&&
1741 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1742 mWaitingToPreview
= null
;
1744 if (mWaitingToSend
!= null
&&
1745 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1746 mWaitingToSend
= null
;
1748 onTransferStateChanged(file
, false
, false
);
1752 public void onRefresh() {
1753 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1754 if (listOfFiles
!= null
) {
1755 OCFile folder
= listOfFiles
.getCurrentFile();
1756 if (folder
!= null
) {
1757 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1758 listDirectory(mFile);*/
1759 startSyncFolderOperation(folder
);
1764 private void sortByDate(boolean ascending
){
1765 getListOfFilesFragment().sortByDate(ascending
);
1768 private void sortBySize(boolean ascending
){
1769 getListOfFilesFragment().sortBySize(ascending
);
1772 private void sortByName(boolean ascending
){
1773 getListOfFilesFragment().sortByName(ascending
);