2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.annotation
.TargetApi
;
29 import android
.support
.v7
.app
.AlertDialog
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.ComponentName
;
32 import android
.content
.ContentResolver
;
33 import android
.content
.Context
;
34 import android
.content
.DialogInterface
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SyncRequest
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Build
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.OpenableColumns
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.support
.v4
.content
.ContextCompat
;
52 import android
.support
.v4
.view
.GravityCompat
;
53 import android
.view
.Menu
;
54 import android
.view
.MenuInflater
;
55 import android
.view
.MenuItem
;
56 import android
.view
.View
;
57 import android
.widget
.ProgressBar
;
58 import android
.widget
.RelativeLayout
;
59 import android
.widget
.TextView
;
60 import android
.widget
.Toast
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.operations
.CopyFileOperation
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.MoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
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
.FileStorageUtils
;
107 import com
.owncloud
.android
.utils
.UriUtils
;
112 * Displays, what files the user has available in his ownCloud.
115 public class FileDisplayActivity
extends HookActivity
116 implements FileFragment
.ContainerActivity
,
117 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
121 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
122 private UploadFinishReceiver mUploadFinishReceiver
;
123 private DownloadFinishReceiver mDownloadFinishReceiver
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
126 private boolean mDualPane
;
127 private View mLeftFragmentContainer
;
128 private View mRightFragmentContainer
;
129 private ProgressBar mProgressBar
;
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 String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 public static final int ACTION_MOVE_FILES
= 3;
140 public static final int ACTION_COPY_FILES
= 4;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
152 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
153 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
154 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
156 private OCFile mWaitingToSend
;
160 protected void onCreate(Bundle savedInstanceState
) {
161 Log_OC
.v(TAG
, "onCreate() start");
163 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
166 /// grant that FileObserverService is watching favorite files
167 if (savedInstanceState
== null
) {
168 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
169 startService(initObserversIntent
);
172 /// Load of saved instance state
173 if(savedInstanceState
!= null
) {
174 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
175 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
178 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
180 mWaitingToPreview
= null
;
181 mSyncInProgress
= false
;
182 mWaitingToSend
= null
;
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
193 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
194 mProgressBar
.setIndeterminateDrawable(
195 ContextCompat
.getDrawable(this,
196 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
198 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
199 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
200 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
201 if (savedInstanceState
== null
) {
202 createMinFragments();
206 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
207 // according to the official
210 // enable ActionBar app icon to behave as action to toggle nav drawer
211 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
212 getSupportActionBar().setHomeButtonEnabled(true
);
214 mProgressBar
.setIndeterminate(mSyncInProgress
);
215 // always AFTER setContentView(...) ; to work around bug in its implementation
219 Log_OC
.v(TAG
, "onCreate() end");
223 protected void onStart() {
224 Log_OC
.v(TAG
, "onStart() start");
226 Log_OC
.v(TAG
, "onStart() end");
230 protected void onDestroy() {
231 Log_OC
.v(TAG
, "onDestroy() start");
233 Log_OC
.v(TAG
, "onDestroy() end");
237 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
240 protected void onAccountSet(boolean stateWasRecovered
) {
241 super.onAccountSet(stateWasRecovered
);
242 if (getAccount() != null
) {
243 /// Check whether the 'main' OCFile handled by the Activity is contained in the
245 OCFile file
= getFile();
246 // get parent from path
247 String parentPath
= "";
249 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
250 // upload in progress - right now, files are not inserted in the local
251 // cache until the upload is successful get parent from path
252 parentPath
= file
.getRemotePath().substring(0,
253 file
.getRemotePath().lastIndexOf(file
.getFileName()));
254 if (getStorageManager().getFileByPath(parentPath
) == null
)
255 file
= null
; // not able to know the directory where the file is uploading
257 file
= getStorageManager().getFileByPath(file
.getRemotePath());
258 // currentDir = null if not in the current Account
262 // fall back to root folder
263 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
267 if (mAccountWasSet
) {
268 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
269 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
270 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
271 int lastAtPos
= getAccount().name
.lastIndexOf("@");
272 username
.setText(getAccount().name
.substring(0, lastAtPos
));
276 if (!stateWasRecovered
) {
277 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
278 initFragmentsWithFile();
279 if (file
.isFolder()) {
280 startSyncFolderOperation(file
, false
);
284 updateFragmentsVisibility(!file
.isFolder());
285 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
290 private void createMinFragments() {
291 OCFileListFragment listOfFiles
= new OCFileListFragment();
292 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
293 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
294 transaction
.commit();
297 private void initFragmentsWithFile() {
298 if (getAccount() != null
&& getFile() != null
) {
300 OCFileListFragment listOfFiles
= getListOfFilesFragment();
301 if (listOfFiles
!= null
) {
302 listOfFiles
.listDirectory(getCurrentDir(), MainApp
.getOnlyOnDevice());
304 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
308 OCFile file
= getFile();
309 Fragment secondFragment
= chooseInitialSecondFragment(file
);
310 if (secondFragment
!= null
) {
311 setSecondFragment(secondFragment
);
312 updateFragmentsVisibility(true
);
313 updateActionBarTitleAndHomeButton(file
);
316 cleanSecondFragment();
317 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
318 startTextPreview(file
);
322 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
323 if (getAccount() == null
) {
324 Log_OC
.wtf(TAG
, "\t account is NULL");
326 if (getFile() == null
) {
327 Log_OC
.wtf(TAG
, "\t file is NULL");
332 private Fragment
chooseInitialSecondFragment(OCFile file
) {
333 Fragment secondFragment
= null
;
334 if (file
!= null
&& !file
.isFolder()) {
335 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
336 && file
.getLastSyncDateForProperties() > 0 // temporal fix
338 int startPlaybackPosition
=
339 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
341 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
342 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
343 startPlaybackPosition
, autoplay
);
345 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
346 secondFragment
= null
;
348 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
351 return secondFragment
;
356 * Replaces the second fragment managed by the activity with the received as
359 * Assumes never will be more than two fragments managed at the same time.
361 * @param fragment New second Fragment to set.
363 private void setSecondFragment(Fragment fragment
) {
364 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
365 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
366 transaction
.commit();
370 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
372 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
373 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
379 } else if (existsSecondFragment
) {
380 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
381 mLeftFragmentContainer
.setVisibility(View
.GONE
);
383 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
384 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
388 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
389 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
391 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
392 mRightFragmentContainer
.setVisibility(View
.GONE
);
398 private OCFileListFragment
getListOfFilesFragment() {
399 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
400 FileDisplayActivity
.TAG_LIST_OF_FILES
);
401 if (listOfFiles
!= null
) {
402 return (OCFileListFragment
) listOfFiles
;
404 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
408 public FileFragment
getSecondFragment() {
409 Fragment second
= getSupportFragmentManager().findFragmentByTag(
410 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
411 if (second
!= null
) {
412 return (FileFragment
) second
;
417 protected void cleanSecondFragment() {
418 Fragment second
= getSecondFragment();
419 if (second
!= null
) {
420 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
424 updateFragmentsVisibility(false
);
425 updateActionBarTitleAndHomeButton(null
);
428 protected void refreshListOfFilesFragment() {
429 OCFileListFragment fileListFragment
= getListOfFilesFragment();
430 if (fileListFragment
!= null
) {
431 fileListFragment
.listDirectory(MainApp
.getOnlyOnDevice());
435 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
437 FileFragment secondFragment
= getSecondFragment();
438 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
439 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
440 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
441 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
442 OCFile fileInFragment
= detailsFragment
.getFile();
443 if (fileInFragment
!= null
&&
444 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
445 // the user browsed to other file ; forget the automatic preview
446 mWaitingToPreview
= null
;
448 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
449 // grant that the right panel updates the progress bar
450 detailsFragment
.listenForTransferProgress();
451 detailsFragment
.updateFileDetails(true
, false
);
453 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
454 // update the right panel
455 boolean detailsFragmentChanged
= false
;
458 mWaitingToPreview
= getStorageManager().getFileById(
459 mWaitingToPreview
.getFileId()); // update the file from database,
460 // for the local storage path
461 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
462 startMediaPreview(mWaitingToPreview
, 0, true
);
463 detailsFragmentChanged
= true
;
464 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
465 startTextPreview(mWaitingToPreview
);
466 detailsFragmentChanged
= true
;
468 getFileOperationsHelper().openFile(mWaitingToPreview
);
471 mWaitingToPreview
= null
;
473 if (!detailsFragmentChanged
) {
474 detailsFragment
.updateFileDetails(false
, (success
));
481 public boolean onPrepareOptionsMenu(Menu menu
) {
482 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
483 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
484 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
485 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
486 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
488 return super.onPrepareOptionsMenu(menu
);
492 public boolean onCreateOptionsMenu(Menu menu
) {
493 MenuInflater inflater
= getMenuInflater();
494 inflater
.inflate(R
.menu
.main_menu
, menu
);
500 public boolean onOptionsItemSelected(MenuItem item
) {
501 boolean retval
= true
;
502 switch (item
.getItemId()) {
503 case R
.id
.action_create_dir
: {
504 CreateFolderDialogFragment dialog
=
505 CreateFolderDialogFragment
.newInstance(getCurrentDir());
506 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
510 case R
.id
.action_sync_account
: {
511 startSynchronization();
514 case R
.id
.action_upload
: {
515 UploadSourceDialogFragment dialog
=
516 UploadSourceDialogFragment
.newInstance(getAccount());
517 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
520 case android
.R
.id
.home
: {
521 FileFragment second
= getSecondFragment();
522 OCFile currentDir
= getCurrentDir();
523 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
524 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
525 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
526 (second
!= null
&& second
.getFile() != null
)) {
530 mDrawerLayout
.openDrawer(GravityCompat
.START
);
534 case R
.id
.action_sort
: {
535 SharedPreferences appPreferences
= PreferenceManager
536 .getDefaultSharedPreferences(this);
538 // Read sorting order, default to sort by name ascending
539 Integer sortOrder
= appPreferences
540 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
542 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
543 builder
.setTitle(R
.string
.actionbar_sort_title
)
544 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
545 new DialogInterface
.OnClickListener() {
546 public void onClick(DialogInterface dialog
, int which
) {
559 builder
.create().show();
563 retval
= super.onOptionsItemSelected(item
);
568 private void startSynchronization() {
569 Log_OC
.d(TAG
, "Got to start sync");
570 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
571 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
572 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
573 // cancel the current synchronizations of any ownCloud account
574 Bundle bundle
= new Bundle();
575 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
576 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
577 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
578 MainApp
.getAuthority());
579 ContentResolver
.requestSync(
581 MainApp
.getAuthority(), bundle
);
583 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
584 MainApp
.getAuthority() + " with new API");
585 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
586 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
587 builder
.setExpedited(true
);
588 builder
.setManual(true
);
591 // Fix bug in Android Lollipop when you click on refresh the whole account
592 Bundle extras
= new Bundle();
593 builder
.setExtras(extras
);
595 SyncRequest request
= builder
.build();
596 ContentResolver
.requestSync(request
);
601 * Called, when the user selected something for uploading
604 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
606 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
608 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
609 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
610 //getClipData is only supported on api level 16+, Jelly Bean
611 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
612 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
613 Intent intent
= new Intent();
614 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
615 requestSimpleUpload(intent
, resultCode
);
618 requestSimpleUpload(data
, resultCode
);
620 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
621 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
622 requestMultipleUpload(data
, resultCode
);
624 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
625 final Intent fData
= data
;
626 final int fResultCode
= resultCode
;
627 getHandler().postDelayed(
631 requestMoveOperation(fData
, fResultCode
);
634 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
637 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
639 final Intent fData
= data
;
640 final int fResultCode
= resultCode
;
641 getHandler().postDelayed(
645 requestCopyOperation(fData
, fResultCode
);
648 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
652 super.onActivityResult(requestCode
, resultCode
, data
);
657 private void requestMultipleUpload(Intent data
, int resultCode
) {
658 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
659 if (filePaths
!= null
) {
660 String
[] remotePaths
= new String
[filePaths
.length
];
661 String remotePathBase
= getCurrentDir().getRemotePath();
662 for (int j
= 0; j
< remotePaths
.length
; j
++) {
663 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
666 Intent i
= new Intent(this, FileUploader
.class);
667 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
668 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
669 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
670 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
671 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
672 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
676 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
677 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
685 private void requestSimpleUpload(Intent data
, int resultCode
) {
686 String filePath
= null
;
687 String mimeType
= null
;
689 Uri selectedImageUri
= data
.getData();
692 mimeType
= getContentResolver().getType(selectedImageUri
);
694 String fileManagerString
= selectedImageUri
.getPath();
695 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
697 if (selectedImagePath
!= null
)
698 filePath
= selectedImagePath
;
700 filePath
= fileManagerString
;
702 } catch (Exception e
) {
703 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
704 "Intent.ACTION_GET_CONTENT", e
);
707 if (filePath
== null
) {
708 Log_OC
.e(TAG
, "Couldn't resolve path to file");
709 Toast t
= Toast
.makeText(
710 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
718 Intent i
= new Intent(this, FileUploader
.class);
719 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
720 OCFile currentDir
= getCurrentDir();
721 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
723 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
724 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
726 if (cursor
!= null
&& cursor
.moveToFirst()) {
727 String displayName
= cursor
.getString(cursor
.getColumnIndex(
728 OpenableColumns
.DISPLAY_NAME
));
729 Log_OC
.v(TAG
, "Display Name: " + displayName
);
731 displayName
.replace(File
.separatorChar
, '_');
732 displayName
.replace(File
.pathSeparatorChar
, '_');
733 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
736 // and what happens in case of error?; wrong target name for the upload
742 remotePath
+= new File(filePath
).getName();
745 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
746 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
747 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
748 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
749 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
750 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
755 * Request the operation for moving the file/folder from one path to another
757 * @param data Intent received
758 * @param resultCode Result code received
760 private void requestMoveOperation(Intent data
, int resultCode
) {
761 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
762 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
763 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
767 * Request the operation for copying the file/folder from one path to another
769 * @param data Intent received
770 * @param resultCode Result code received
772 private void requestCopyOperation(Intent data
, int resultCode
) {
773 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
774 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
775 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
779 public void onBackPressed() {
780 if (!isDrawerOpen()){
781 OCFileListFragment listOfFiles
= getListOfFilesFragment();
782 if (mDualPane
|| getSecondFragment() == null
) {
783 OCFile currentDir
= getCurrentDir();
784 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
788 if (listOfFiles
!= null
) { // should never be null, indeed
789 listOfFiles
.onBrowseUp();
792 if (listOfFiles
!= null
) { // should never be null, indeed
793 setFile(listOfFiles
.getCurrentFile());
795 cleanSecondFragment();
797 super.onBackPressed();
802 protected void onSaveInstanceState(Bundle outState
) {
803 // responsibility of restore is preferred in onCreate() before than in
804 // onRestoreInstanceState when there are Fragments involved
805 Log_OC
.v(TAG
, "onSaveInstanceState() start");
806 super.onSaveInstanceState(outState
);
807 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
808 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
809 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
810 // mRefreshSharesInProgress);
811 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
813 Log_OC
.v(TAG
, "onSaveInstanceState() end");
818 protected void onResume() {
819 Log_OC
.v(TAG
, "onResume() start");
821 // refresh Navigation Drawer account list
822 mNavigationDrawerAdapter
.updateAccountList();
824 // refresh list of files
825 refreshListOfFilesFragment();
827 // Listen for sync messages
828 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
829 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
830 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
831 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
832 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
833 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
834 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
835 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
836 // syncIntentFilter);
838 // Listen for upload messages
839 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
840 mUploadFinishReceiver
= new UploadFinishReceiver();
841 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
843 // Listen for download messages
844 IntentFilter downloadIntentFilter
= new IntentFilter(
845 FileDownloader
.getDownloadAddedMessage());
846 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
847 mDownloadFinishReceiver
= new DownloadFinishReceiver();
848 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
850 Log_OC
.v(TAG
, "onResume() end");
856 protected void onPause() {
857 Log_OC
.v(TAG
, "onPause() start");
858 if (mSyncBroadcastReceiver
!= null
) {
859 unregisterReceiver(mSyncBroadcastReceiver
);
860 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
861 mSyncBroadcastReceiver
= null
;
863 if (mUploadFinishReceiver
!= null
) {
864 unregisterReceiver(mUploadFinishReceiver
);
865 mUploadFinishReceiver
= null
;
867 if (mDownloadFinishReceiver
!= null
) {
868 unregisterReceiver(mDownloadFinishReceiver
);
869 mDownloadFinishReceiver
= null
;
873 Log_OC
.v(TAG
, "onPause() end");
877 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
880 * {@link BroadcastReceiver} to enable syncing feedback in UI
883 public void onReceive(Context context
, Intent intent
) {
885 String event
= intent
.getAction();
886 Log_OC
.d(TAG
, "Received broadcast " + event
);
887 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
888 String synchFolderRemotePath
=
889 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
890 RemoteOperationResult synchResult
=
891 (RemoteOperationResult
)intent
.getSerializableExtra(
892 FileSyncAdapter
.EXTRA_RESULT
);
893 boolean sameAccount
= (getAccount() != null
&&
894 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
898 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
899 mSyncInProgress
= true
;
902 OCFile currentFile
= (getFile() == null
) ? null
:
903 getStorageManager().getFileByPath(getFile().getRemotePath());
904 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
905 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
907 if (currentDir
== null
) {
908 // current folder was removed from the server
909 Toast
.makeText( FileDisplayActivity
.this,
912 sync_current_folder_was_removed
),
913 synchFolderRemotePath
),
920 if (currentFile
== null
&& !getFile().isFolder()) {
921 // currently selected file was removed in the server, and now we
923 cleanSecondFragment();
924 currentFile
= currentDir
;
927 if (synchFolderRemotePath
!= null
&&
928 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
929 OCFileListFragment fileListFragment
= getListOfFilesFragment();
930 if (fileListFragment
!= null
) {
931 fileListFragment
.listDirectory(currentDir
,
932 MainApp
.getOnlyOnDevice());
935 setFile(currentFile
);
938 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
939 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
942 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
943 equals(event
) &&/// TODO refactor and make common
945 synchResult
!= null
&& !synchResult
.isSuccess() &&
946 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
947 synchResult
.isIdPRedirection() ||
948 (synchResult
.isException() && synchResult
.getException()
949 instanceof AuthenticatorException
))) {
953 OwnCloudClient client
;
954 OwnCloudAccount ocAccount
=
955 new OwnCloudAccount(getAccount(), context
);
956 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
957 removeClientFor(ocAccount
));
958 if (client
!= null
) {
959 OwnCloudCredentials cred
= client
.getCredentials();
961 AccountManager am
= AccountManager
.get(context
);
962 if (cred
.authTokenExpires()) {
963 am
.invalidateAuthToken(
968 am
.clearPassword(getAccount());
972 requestCredentialsUpdate();
974 } catch (AccountNotFoundException e
) {
975 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
980 removeStickyBroadcast(intent
);
981 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
982 mProgressBar
.setIndeterminate(mSyncInProgress
);
983 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
984 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
985 /*|| mRefreshSharesInProgress*/ //);
991 if (synchResult
!= null
) {
992 if (synchResult
.getCode().equals(
993 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
994 mLastSslUntrustedServerResult
= synchResult
;
997 } catch (RuntimeException e
) {
998 // avoid app crashes after changing the serial id of RemoteOperationResult
999 // in owncloud library with broadcast notifications pending to process
1000 removeStickyBroadcast(intent
);
1006 * Show a text message on screen view for notifying user if content is
1007 * loading or folder is empty
1009 private void setBackgroundText() {
1010 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1011 if (ocFileListFragment
!= null
) {
1012 int message
= R
.string
.file_list_loading
;
1013 if (!mSyncInProgress
) {
1014 // In case file list is empty
1015 message
= R
.string
.file_list_empty
;
1017 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1019 Log_OC
.e(TAG
, "OCFileListFragment is null");
1024 * Once the file upload has finished -> update view
1026 private class UploadFinishReceiver
extends BroadcastReceiver
{
1028 * Once the file upload has finished -> update view
1030 * @author David A. Velasco
1031 * {@link BroadcastReceiver} to enable upload feedback in UI
1034 public void onReceive(Context context
, Intent intent
) {
1036 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1037 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1038 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1039 OCFile currentDir
= getCurrentDir();
1040 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1041 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1043 if (sameAccount
&& isDescendant
) {
1044 refreshListOfFilesFragment();
1047 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1049 boolean renamedInUpload
= getFile().getRemotePath().
1050 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1051 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1053 FileFragment details
= getSecondFragment();
1054 boolean detailFragmentIsShown
= (details
!= null
&&
1055 details
instanceof FileDetailFragment
);
1057 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1058 if (uploadWasFine
) {
1059 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1061 if (renamedInUpload
) {
1062 String newName
= (new File(uploadedRemotePath
)).getName();
1063 Toast msg
= Toast
.makeText(
1066 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1071 if (uploadWasFine
|| getFile().fileExists()) {
1072 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1074 cleanSecondFragment();
1077 // Force the preview if the file is an image or text file
1078 if (uploadWasFine
) {
1079 OCFile ocFile
= getFile();
1080 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1081 startImagePreview(getFile());
1082 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1083 startTextPreview(ocFile
);
1084 // TODO what about other kind of previews?
1088 mProgressBar
.setIndeterminate(false
);
1090 if (intent
!= null
) {
1091 removeStickyBroadcast(intent
);
1101 * Class waiting for broadcast events from the {@link FileDownloader} service.
1103 * Updates the UI when a download is started or finished, provided that it is relevant for the
1106 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1108 //int refreshCounter = 0;
1110 public void onReceive(Context context
, Intent intent
) {
1112 boolean sameAccount
= isSameAccount(context
, intent
);
1113 String downloadedRemotePath
=
1114 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1115 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1117 if (sameAccount
&& isDescendant
) {
1118 String linkedToRemotePath
=
1119 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1120 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1121 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1122 refreshListOfFilesFragment();
1124 refreshSecondFragment(
1126 downloadedRemotePath
,
1127 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1131 if (mWaitingToSend
!= null
) {
1133 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1134 if (mWaitingToSend
.isDown()) {
1135 sendDownloadedFile();
1140 if (intent
!= null
) {
1141 removeStickyBroadcast(intent
);
1146 private boolean isDescendant(String downloadedRemotePath
) {
1147 OCFile currentDir
= getCurrentDir();
1149 currentDir
!= null
&&
1150 downloadedRemotePath
!= null
&&
1151 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1155 private boolean isAscendant(String linkedToRemotePath
) {
1156 OCFile currentDir
= getCurrentDir();
1158 currentDir
!= null
&&
1159 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1163 private boolean isSameAccount(Context context
, Intent intent
) {
1164 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1165 return (accountName
!= null
&& getAccount() != null
&&
1166 accountName
.equals(getAccount().name
));
1171 public void browseToRoot() {
1172 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1173 if (listOfFiles
!= null
) { // should never be null, indeed
1174 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1175 listOfFiles
.listDirectory(root
, MainApp
.getOnlyOnDevice());
1176 setFile(listOfFiles
.getCurrentFile());
1177 startSyncFolderOperation(root
, false
);
1179 cleanSecondFragment();
1186 * Updates action bar and second fragment, if in dual pane mode.
1189 public void onBrowsedDownTo(OCFile directory
) {
1191 cleanSecondFragment();
1193 startSyncFolderOperation(directory
, false
);
1197 * Shows the information of the {@link OCFile} received as a
1198 * parameter in the second fragment.
1200 * @param file {@link OCFile} whose details will be shown
1203 public void showDetails(OCFile file
) {
1204 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1205 setSecondFragment(detailFragment
);
1206 updateFragmentsVisibility(true
);
1207 updateActionBarTitleAndHomeButton(file
);
1212 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1214 // in dual pane mode, keep the focus of title an action bar in the current folder
1215 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1218 super.updateActionBarTitleAndHomeButton(chosenFile
);
1224 protected ServiceConnection
newTransferenceServiceConnection() {
1225 return new ListServiceConnection();
1229 * Defines callbacks for service binding, passed to bindService()
1231 private class ListServiceConnection
implements ServiceConnection
{
1234 public void onServiceConnected(ComponentName component
, IBinder service
) {
1235 if (component
.equals(new ComponentName(
1236 FileDisplayActivity
.this, FileDownloader
.class))) {
1237 Log_OC
.d(TAG
, "Download service connected");
1238 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1239 if (mWaitingToPreview
!= null
)
1240 if (getStorageManager() != null
) {
1243 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1244 if (!mWaitingToPreview
.isDown()) {
1245 requestForDownload();
1249 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1250 FileUploader
.class))) {
1251 Log_OC
.d(TAG
, "Upload service connected");
1252 mUploaderBinder
= (FileUploaderBinder
) service
;
1256 // a new chance to get the mDownloadBinder through
1257 // getFileDownloadBinder() - THIS IS A MESS
1258 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1259 if (listOfFiles
!= null
) {
1260 listOfFiles
.listDirectory(MainApp
.getOnlyOnDevice());
1262 FileFragment secondFragment
= getSecondFragment();
1263 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1264 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1265 detailFragment
.listenForTransferProgress();
1266 detailFragment
.updateFileDetails(false
, false
);
1271 public void onServiceDisconnected(ComponentName component
) {
1272 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1273 FileDownloader
.class))) {
1274 Log_OC
.d(TAG
, "Download service disconnected");
1275 mDownloaderBinder
= null
;
1276 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1277 FileUploader
.class))) {
1278 Log_OC
.d(TAG
, "Upload service disconnected");
1279 mUploaderBinder
= null
;
1285 public void onSavedCertificate() {
1286 startSyncFolderOperation(getCurrentDir(), false
);
1291 public void onFailedSavingCertificate() {
1292 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1293 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1295 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1299 public void onCancelCertificate() {
1304 * Updates the view associated to the activity after the finish of some operation over files
1305 * in the current account.
1307 * @param operation Removal operation performed.
1308 * @param result Result of the removal.
1311 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1312 super.onRemoteOperationFinish(operation
, result
);
1314 if (operation
instanceof RemoveFileOperation
) {
1315 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1317 } else if (operation
instanceof RenameFileOperation
) {
1318 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1320 } else if (operation
instanceof SynchronizeFileOperation
) {
1321 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1323 } else if (operation
instanceof CreateFolderOperation
) {
1324 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1326 } else if (operation
instanceof CreateShareOperation
) {
1327 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1329 } else if (operation
instanceof UnshareLinkOperation
) {
1330 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1332 } else if (operation
instanceof MoveFileOperation
) {
1333 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1335 } else if (operation
instanceof CopyFileOperation
) {
1336 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1340 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1341 RemoteOperationResult result
) {
1342 if (result
.isSuccess()) {
1343 refreshShowDetails();
1344 refreshListOfFilesFragment();
1348 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1349 RemoteOperationResult result
) {
1350 if (result
.isSuccess()) {
1351 refreshShowDetails();
1352 refreshListOfFilesFragment();
1354 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1355 cleanSecondFragment();
1356 refreshListOfFilesFragment();
1360 private void refreshShowDetails() {
1361 FileFragment details
= getSecondFragment();
1362 if (details
!= null
) {
1363 OCFile file
= details
.getFile();
1365 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1366 if (details
instanceof PreviewMediaFragment
) {
1367 // Refresh OCFile of the fragment
1368 ((PreviewMediaFragment
) details
).updateFile(file
);
1369 } else if (details
instanceof PreviewTextFragment
) {
1370 // Refresh OCFile of the fragment
1371 ((PreviewTextFragment
) details
).updateFile(file
);
1376 invalidateOptionsMenu();
1381 * Updates the view associated to the activity after the finish of an operation trying to
1384 * @param operation Removal operation performed.
1385 * @param result Result of the removal.
1387 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1388 RemoteOperationResult result
) {
1389 dismissLoadingDialog();
1391 Toast msg
= Toast
.makeText(this,
1392 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1396 if (result
.isSuccess()) {
1397 OCFile removedFile
= operation
.getFile();
1398 FileFragment second
= getSecondFragment();
1399 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1400 if (second
instanceof PreviewMediaFragment
) {
1401 ((PreviewMediaFragment
) second
).stopPreview(true
);
1403 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1404 cleanSecondFragment();
1406 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1407 refreshListOfFilesFragment();
1409 invalidateOptionsMenu();
1411 if (result
.isSslRecoverableException()) {
1412 mLastSslUntrustedServerResult
= result
;
1413 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1420 * Updates the view associated to the activity after the finish of an operation trying to move a
1423 * @param operation Move operation performed.
1424 * @param result Result of the move operation.
1426 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1427 RemoteOperationResult result
) {
1428 if (result
.isSuccess()) {
1429 dismissLoadingDialog();
1430 refreshListOfFilesFragment();
1432 dismissLoadingDialog();
1434 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1435 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1439 } catch (NotFoundException e
) {
1440 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1446 * Updates the view associated to the activity after the finish of an operation trying to copy a
1449 * @param operation Copy operation performed.
1450 * @param result Result of the copy operation.
1452 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1453 if (result
.isSuccess()) {
1454 dismissLoadingDialog();
1455 refreshListOfFilesFragment();
1457 dismissLoadingDialog();
1459 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1460 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1464 } catch (NotFoundException e
) {
1465 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1471 * Updates the view associated to the activity after the finish of an operation trying to rename
1474 * @param operation Renaming operation performed.
1475 * @param result Result of the renaming.
1477 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1478 RemoteOperationResult result
) {
1479 dismissLoadingDialog();
1480 OCFile renamedFile
= operation
.getFile();
1481 if (result
.isSuccess()) {
1482 FileFragment details
= getSecondFragment();
1483 if (details
!= null
) {
1484 if (details
instanceof FileDetailFragment
&&
1485 renamedFile
.equals(details
.getFile()) ) {
1486 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1487 showDetails(renamedFile
);
1489 } else if (details
instanceof PreviewMediaFragment
&&
1490 renamedFile
.equals(details
.getFile())) {
1491 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1492 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1493 int position
= ((PreviewMediaFragment
) details
).getPosition();
1494 startMediaPreview(renamedFile
, position
, true
);
1496 getFileOperationsHelper().openFile(renamedFile
);
1498 } else if (details
instanceof PreviewTextFragment
&&
1499 renamedFile
.equals(details
.getFile())) {
1500 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1501 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1502 startTextPreview(renamedFile
);
1504 getFileOperationsHelper().openFile(renamedFile
);
1509 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1510 refreshListOfFilesFragment();
1514 Toast msg
= Toast
.makeText(this,
1515 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1519 if (result
.isSslRecoverableException()) {
1520 mLastSslUntrustedServerResult
= result
;
1521 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1526 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1527 RemoteOperationResult result
) {
1528 if (result
.isSuccess()) {
1529 if (operation
.transferWasRequested()) {
1530 OCFile syncedFile
= operation
.getLocalFile();
1531 onTransferStateChanged(syncedFile
, true
, true
);
1532 invalidateOptionsMenu();
1533 refreshShowDetails();
1539 * Updates the view associated to the activity after the finish of an operation trying create a
1542 * @param operation Creation operation performed.
1543 * @param result Result of the creation.
1545 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1546 RemoteOperationResult result
) {
1547 if (result
.isSuccess()) {
1548 dismissLoadingDialog();
1549 refreshListOfFilesFragment();
1551 dismissLoadingDialog();
1553 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1554 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1558 } catch (NotFoundException e
) {
1559 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1569 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1570 refreshListOfFilesFragment();
1571 FileFragment details
= getSecondFragment();
1572 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1573 file
.equals(details
.getFile()) ) {
1574 if (downloading
|| uploading
) {
1575 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1577 if (!file
.fileExists()) {
1578 cleanSecondFragment();
1580 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1588 private void requestForDownload() {
1589 Account account
= getAccount();
1590 //if (!mWaitingToPreview.isDownloading()) {
1591 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1592 Intent i
= new Intent(this, FileDownloader
.class);
1593 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1594 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1600 private OCFile
getCurrentDir() {
1601 OCFile file
= getFile();
1603 if (file
.isFolder()) {
1605 } else if (getStorageManager() != null
) {
1606 String parentPath
= file
.getRemotePath().substring(0,
1607 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1608 return getStorageManager().getFileByPath(parentPath
);
1614 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1615 long currentSyncTime
= System
.currentTimeMillis();
1617 mSyncInProgress
= true
;
1619 // perform folder synchronization
1620 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1623 getFileOperationsHelper().isSharedSupported(),
1625 getStorageManager(),
1627 getApplicationContext()
1629 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1631 mProgressBar
.setIndeterminate(true
);
1633 setBackgroundText();
1637 * Show untrusted cert dialog
1639 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1640 // Show a dialog with the certificate info
1641 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1642 (CertificateCombinedException
) result
.getException());
1643 FragmentManager fm
= getSupportFragmentManager();
1644 FragmentTransaction ft
= fm
.beginTransaction();
1645 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1648 private void requestForDownload(OCFile file
) {
1649 Account account
= getAccount();
1650 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1651 Intent i
= new Intent(this, FileDownloader
.class);
1652 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1653 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1658 private void sendDownloadedFile() {
1659 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1660 mWaitingToSend
= null
;
1665 * Requests the download of the received {@link OCFile} , updates the UI
1666 * to monitor the download progress and prepares the activity to send the file
1667 * when the download finishes.
1669 * @param file {@link OCFile} to download and preview.
1671 public void startDownloadForSending(OCFile file
) {
1672 mWaitingToSend
= file
;
1673 requestForDownload(mWaitingToSend
);
1674 boolean hasSecondFragment
= (getSecondFragment() != null
);
1675 updateFragmentsVisibility(hasSecondFragment
);
1679 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1681 * @param file Image {@link OCFile} to show.
1683 public void startImagePreview(OCFile file
) {
1684 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1685 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1686 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1687 startActivity(showDetailsIntent
);
1691 * Stars the preview of an already down media {@link OCFile}.
1693 * @param file Media {@link OCFile} to preview.
1694 * @param startPlaybackPosition Media position where the playback will be started,
1696 * @param autoplay When 'true', the playback will start without user
1699 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1700 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1702 setSecondFragment(mediaFragment
);
1703 updateFragmentsVisibility(true
);
1704 updateActionBarTitleAndHomeButton(file
);
1709 * Stars the preview of a text file {@link OCFile}.
1711 * @param file Text {@link OCFile} to preview.
1713 public void startTextPreview(OCFile file
) {
1714 Bundle args
= new Bundle();
1715 args
.putParcelable(EXTRA_FILE
, file
);
1716 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1717 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1718 PreviewTextFragment
.class.getName(), args
);
1719 setSecondFragment(textPreviewFragment
);
1720 updateFragmentsVisibility(true
);
1721 //updateNavigationElementsInActionBar(file);
1726 * Requests the download of the received {@link OCFile} , updates the UI
1727 * to monitor the download progress and prepares the activity to preview
1728 * or open the file when the download finishes.
1730 * @param file {@link OCFile} to download and preview.
1732 public void startDownloadForPreview(OCFile file
) {
1733 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1734 setSecondFragment(detailFragment
);
1735 mWaitingToPreview
= file
;
1736 requestForDownload();
1737 updateFragmentsVisibility(true
);
1738 updateActionBarTitleAndHomeButton(file
);
1743 public void cancelTransference(OCFile file
) {
1744 getFileOperationsHelper().cancelTransference(file
);
1745 if (mWaitingToPreview
!= null
&&
1746 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1747 mWaitingToPreview
= null
;
1749 if (mWaitingToSend
!= null
&&
1750 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1751 mWaitingToSend
= null
;
1753 onTransferStateChanged(file
, false
, false
);
1757 public void onRefresh(boolean ignoreETag
) {
1758 refreshList(ignoreETag
);
1762 public void onRefresh() {
1766 private void refreshList(boolean ignoreETag
) {
1767 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1768 if (listOfFiles
!= null
) {
1769 OCFile folder
= listOfFiles
.getCurrentFile();
1770 if (folder
!= null
) {
1771 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1772 listDirectory(mFile);*/
1773 startSyncFolderOperation(folder
, ignoreETag
);
1778 private void sortByDate(boolean ascending
) {
1779 getListOfFilesFragment().sortByDate(ascending
);
1782 private void sortBySize(boolean ascending
) {
1783 getListOfFilesFragment().sortBySize(ascending
);
1786 private void sortByName(boolean ascending
) {
1787 getListOfFilesFragment().sortByName(ascending
);
1790 public void allFilesOption() {