1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
21 import android
.accounts
.Account
;
22 import android
.accounts
.AccountManager
;
23 import android
.accounts
.AuthenticatorException
;
24 import android
.accounts
.OperationCanceledException
;
25 import android
.app
.AlertDialog
;
26 import android
.app
.Dialog
;
27 import android
.app
.ProgressDialog
;
28 import android
.content
.BroadcastReceiver
;
29 import android
.content
.ComponentName
;
30 import android
.content
.ContentResolver
;
31 import android
.content
.ContentUris
;
32 import android
.content
.Context
;
33 import android
.content
.DialogInterface
;
34 import android
.content
.Intent
;
35 import android
.content
.IntentFilter
;
36 import android
.content
.ServiceConnection
;
37 import android
.content
.SharedPreferences
;
38 import android
.content
.SyncRequest
;
39 import android
.content
.res
.Resources
.NotFoundException
;
40 import android
.database
.Cursor
;
41 import android
.net
.Uri
;
42 import android
.os
.Build
;
43 import android
.os
.Bundle
;
44 import android
.os
.Environment
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.DocumentsContract
;
48 import android
.provider
.MediaStore
;
49 import android
.provider
.OpenableColumns
;
50 import android
.support
.v4
.app
.Fragment
;
51 import android
.support
.v4
.app
.FragmentManager
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.util
.Log
;
54 import android
.view
.View
;
55 import android
.view
.ViewGroup
;
56 import android
.widget
.ArrayAdapter
;
57 import android
.widget
.TextView
;
58 import android
.widget
.Toast
;
60 import com
.actionbarsherlock
.app
.ActionBar
;
61 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
62 import com
.actionbarsherlock
.view
.Menu
;
63 import com
.actionbarsherlock
.view
.MenuInflater
;
64 import com
.actionbarsherlock
.view
.MenuItem
;
65 import com
.actionbarsherlock
.view
.Window
;
66 import com
.owncloud
.android
.BuildConfig
;
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
.lib
.common
.utils
.Log_OC
;
84 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
85 import com
.owncloud
.android
.operations
.CreateShareOperation
;
86 import com
.owncloud
.android
.operations
.MoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
88 import com
.owncloud
.android
.operations
.RenameFileOperation
;
89 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
90 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
91 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
92 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
93 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
94 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
95 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
96 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
97 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
98 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
100 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
105 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
106 import com
.owncloud
.android
.utils
.DisplayUtils
;
107 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
108 import com
.owncloud
.android
.utils
.UriUtils
;
111 import java
.io
.IOException
;
115 * Displays, what files the user has available in his ownCloud.
117 * @author Bartek Przybylski
118 * @author David A. Velasco
121 public class FileDisplayActivity
extends HookActivity
implements
122 FileFragment
.ContainerActivity
, OnNavigationListener
,
123 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
125 private ArrayAdapter
<String
> mDirectories
;
127 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
128 private UploadFinishReceiver mUploadFinishReceiver
;
129 private DownloadFinishReceiver mDownloadFinishReceiver
;
130 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
132 private boolean mDualPane
;
133 private View mLeftFragmentContainer
;
134 private View mRightFragmentContainer
;
136 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
137 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
138 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
140 public static final int DIALOG_SHORT_WAIT
= 0;
141 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
142 private static final int DIALOG_CERT_NOT_SAVED
= 2;
144 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
146 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
147 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
148 public static final int ACTION_MOVE_FILES
= 3;
150 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
152 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
153 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
155 private OCFile mWaitingToPreview
;
157 private boolean mSyncInProgress
= false
;
159 private String DIALOG_UNTRUSTED_CERT
;
161 private OCFile mWaitingToSend
;
164 protected void onCreate(Bundle savedInstanceState
) {
165 Log_OC
.d(TAG
, "onCreate() start");
166 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
168 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
170 // PIN CODE request ; best location is to decide, let's try this first
171 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
173 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
177 /// grant that FileObserverService is watching favourite files
178 if (savedInstanceState
== null
) {
179 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
180 startService(initObserversIntent
);
183 /// Load of saved instance state
184 if (savedInstanceState
!= null
) {
185 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
186 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
187 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
190 mWaitingToPreview
= null
;
191 mSyncInProgress
= false
;
192 mWaitingToSend
= null
;
197 // Inflate and set the layout view
198 setContentView(R
.layout
.files
);
199 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
200 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
201 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
202 if (savedInstanceState
== null
) {
203 createMinFragments();
207 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
208 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
209 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
213 Log_OC
.d(TAG
, "onCreate() end");
217 protected void onStart() {
219 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
223 protected void onDestroy() {
228 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
231 protected void onAccountSet(boolean stateWasRecovered
) {
232 super.onAccountSet(stateWasRecovered
);
233 if (getAccount() != null
) {
234 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
235 OCFile file
= getFile();
236 // get parent from path
237 String parentPath
= "";
239 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
240 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
241 // get parent from path
242 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
243 if (getStorageManager().getFileByPath(parentPath
) == null
)
244 file
= null
; // not able to know the directory where the file is uploading
246 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
250 // fall back to root folder
251 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
254 setNavigationListWithFolder(file
);
256 if (!stateWasRecovered
) {
257 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
258 initFragmentsWithFile();
259 if (file
.isFolder()) {
260 startSyncFolderOperation(file
, false
);
264 updateFragmentsVisibility(!file
.isFolder());
265 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
271 private void setNavigationListWithFolder(OCFile file
) {
272 mDirectories
.clear();
273 OCFile fileIt
= file
;
275 while (fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
276 if (fileIt
.isFolder()) {
277 mDirectories
.add(fileIt
.getFileName());
279 // get parent from path
280 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
281 fileIt
= getStorageManager().getFileByPath(parentPath
);
283 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
287 private void createMinFragments() {
288 OCFileListFragment listOfFiles
= new OCFileListFragment();
289 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
290 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
291 transaction
.commit();
294 private void initFragmentsWithFile() {
295 if (getAccount() != null
&& getFile() != null
) {
297 OCFileListFragment listOfFiles
= getListOfFilesFragment();
298 if (listOfFiles
!= null
) {
299 listOfFiles
.listDirectory(getCurrentDir());
301 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
305 OCFile file
= getFile();
306 Fragment secondFragment
= chooseInitialSecondFragment(file
);
307 if (secondFragment
!= null
) {
308 setSecondFragment(secondFragment
);
309 updateFragmentsVisibility(true
);
310 updateNavigationElementsInActionBar(file
);
313 cleanSecondFragment();
314 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
315 startTextPreview(file
);
319 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
320 if (getAccount() == null
) {
321 Log_OC
.wtf(TAG
, "\t account is NULL");
323 if (getFile() == null
) {
324 Log_OC
.wtf(TAG
, "\t file is NULL");
329 private Fragment
chooseInitialSecondFragment(OCFile file
) {
330 Fragment secondFragment
= null
;
331 if (file
!= null
&& !file
.isFolder()) {
332 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
333 && file
.getLastSyncDateForProperties() > 0 // temporal fix
335 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
336 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
337 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
339 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
340 secondFragment
= null
;
341 } else secondFragment
= new FileDetailFragment(file
, getAccount());
343 return secondFragment
;
348 * Replaces the second fragment managed by the activity with the received as
351 * Assumes never will be more than two fragments managed at the same time.
353 * @param fragment New second Fragment to set.
355 private void setSecondFragment(Fragment fragment
) {
356 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
357 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
358 transaction
.commit();
362 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
364 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
371 } else if (existsSecondFragment
) {
372 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
373 mLeftFragmentContainer
.setVisibility(View
.GONE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
380 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
381 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
383 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
384 mRightFragmentContainer
.setVisibility(View
.GONE
);
390 private OCFileListFragment
getListOfFilesFragment() {
391 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
392 if (listOfFiles
!= null
) {
393 return (OCFileListFragment
) listOfFiles
;
395 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
399 public FileFragment
getSecondFragment() {
400 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
401 if (second
!= null
) {
402 return (FileFragment
) second
;
407 protected void cleanSecondFragment() {
408 Fragment second
= getSecondFragment();
409 if (second
!= null
) {
410 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
414 updateFragmentsVisibility(false
);
415 updateNavigationElementsInActionBar(null
);
418 protected void refreshListOfFilesFragment() {
419 OCFileListFragment fileListFragment
= getListOfFilesFragment();
420 if (fileListFragment
!= null
) {
421 fileListFragment
.listDirectory();
425 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
426 FileFragment secondFragment
= getSecondFragment();
427 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
428 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
429 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
430 OCFile fileInFragment
= detailsFragment
.getFile();
431 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
432 // the user browsed to other file ; forget the automatic preview
433 mWaitingToPreview
= null
;
435 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
436 // grant that the right panel updates the progress bar
437 detailsFragment
.listenForTransferProgress();
438 detailsFragment
.updateFileDetails(true
, false
);
440 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
441 // update the right panel
442 boolean detailsFragmentChanged
= false
;
445 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
446 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
447 startMediaPreview(mWaitingToPreview
, 0, true
);
448 detailsFragmentChanged
= true
;
449 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
450 startTextPreview(mWaitingToPreview
);
451 detailsFragmentChanged
= true
;
453 getFileOperationsHelper().openFile(mWaitingToPreview
);
456 mWaitingToPreview
= null
;
458 if (!detailsFragmentChanged
) {
459 detailsFragment
.updateFileDetails(false
, (success
));
466 public boolean onPrepareOptionsMenu(Menu menu
) {
467 if (BuildConfig
.DEBUG
) {
468 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
470 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
472 return super.onPrepareOptionsMenu(menu
);
476 public boolean onCreateOptionsMenu(Menu menu
) {
477 MenuInflater inflater
= getSherlock().getMenuInflater();
478 inflater
.inflate(R
.menu
.main_menu
, menu
);
483 public boolean onOptionsItemSelected(MenuItem item
) {
484 boolean retval
= true
;
485 switch (item
.getItemId()) {
486 case R
.id
.action_create_dir
: {
487 CreateFolderDialogFragment dialog
=
488 CreateFolderDialogFragment
.newInstance(getCurrentDir());
489 dialog
.show(getSupportFragmentManager(), "createdirdialog");
492 case R
.id
.action_sort
: {
493 SharedPreferences appPreferences
= PreferenceManager
494 .getDefaultSharedPreferences(this);
496 // Read sorting order, default to sort by name ascending
497 Integer sortOrder
= appPreferences
498 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
500 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
501 builder
.setTitle(R
.string
.actionbar_sort_title
)
502 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
503 public void onClick(DialogInterface dialog
, int which
) {
513 // TODO re-enable when server-side folder size calculation is available
515 // sortBySize(false);
523 builder
.create().show();
526 case R
.id
.action_sync_account
: {
527 startSynchronization();
530 case R
.id
.action_upload
: {
531 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
534 case R
.id
.action_settings
: {
535 Intent settingsIntent
= new Intent(this, Preferences
.class);
536 startActivity(settingsIntent
);
539 case R
.id
.action_logger
: {
540 Intent loggerIntent
= new Intent(getApplicationContext(), LogHistoryActivity
.class);
541 startActivity(loggerIntent
);
544 case android
.R
.id
.home
: {
545 FileFragment second
= getSecondFragment();
546 OCFile currentDir
= getCurrentDir();
547 if ((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
548 (second
!= null
&& second
.getFile() != null
)) {
555 retval
= super.onOptionsItemSelected(item
);
560 private void startSynchronization() {
561 Log_OC
.e(TAG
, "Got to start sync");
562 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
563 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
564 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
565 Bundle bundle
= new Bundle();
566 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
567 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
568 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
569 ContentResolver
.requestSync(
571 MainApp
.getAuthority(), bundle
);
573 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
574 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
575 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
576 builder
.setExpedited(true
);
577 builder
.setManual(true
);
580 // Fix bug in Android Lollipop when you click on refresh the whole account
581 Bundle extras
= new Bundle();
582 builder
.setExtras(extras
);
584 SyncRequest request
= builder
.build();
585 ContentResolver
.requestSync(request
);
591 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
592 if (itemPosition
!= 0) {
593 String targetPath
= "";
594 for (int i
= itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
595 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
597 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
598 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
599 if (targetFolder
!= null
) {
600 browseTo(targetFolder
);
603 // the next operation triggers a new call to this method, but it's necessary to
604 // ensure that the name exposed in the action bar is the current directory when the
605 // user selected it in the navigation list
606 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
607 getSupportActionBar().setSelectedNavigationItem(0);
613 * Called, when the user selected something for uploading
615 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
616 super.onActivityResult(requestCode
, resultCode
, data
);
618 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
619 requestSimpleUpload(data
, resultCode
);
621 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
622 requestMultipleUpload(data
, resultCode
);
624 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
) {
626 final Intent fData
= data
;
627 final int fResultCode
= resultCode
;
628 getHandler().postDelayed(
632 requestMoveOperation(fData
, fResultCode
);
635 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
640 private void requestMultipleUpload(Intent data
, int resultCode
) {
641 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
642 if (filePaths
!= null
) {
643 String
[] remotePaths
= new String
[filePaths
.length
];
644 String remotePathBase
= "";
645 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
646 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
648 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
649 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
650 for (int j
= 0; j
< remotePaths
.length
; j
++) {
651 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
654 Intent i
= new Intent(this, FileUploader
.class);
655 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
656 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
657 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
658 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
659 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
660 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
664 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
665 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
672 private void requestSimpleUpload(Intent data
, int resultCode
) {
673 String filepath
= null
;
674 String mimeType
= null
;
676 Uri selectedImageUri
= data
.getData();
679 mimeType
= getContentResolver().getType(selectedImageUri
);
681 String filemanagerstring
= selectedImageUri
.getPath();
682 String selectedImagePath
= getPath(selectedImageUri
);
684 if (selectedImagePath
!= null
)
685 filepath
= selectedImagePath
;
687 filepath
= filemanagerstring
;
689 } catch (Exception e
) {
690 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
694 if (filepath
== null
) {
695 Log_OC
.e(TAG
, "Couldnt resolve path to file");
696 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
702 Intent i
= new Intent(this, FileUploader
.class);
703 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
705 String remotepath
= new String();
706 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
707 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
709 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
710 remotepath
+= OCFile
.PATH_SEPARATOR
;
712 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
714 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
715 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
718 if (cursor
!= null
&& cursor
.moveToFirst()) {
719 String displayName
= cursor
.getString(
720 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
721 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
723 displayName
.replace(File
.separatorChar
, '_');
724 displayName
.replace(File
.pathSeparatorChar
, '_');
725 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
733 remotepath
+= new File(filepath
).getName();
736 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
737 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
738 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
739 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
740 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
741 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
746 * Request the operation for moving the file/folder from one path to another
748 * @param data Intent received
749 * @param resultCode Result code received
751 private void requestMoveOperation(Intent data
, int resultCode
) {
752 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
753 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
754 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
758 public void onBackPressed() {
759 OCFileListFragment listOfFiles
= getListOfFilesFragment();
760 if (mDualPane
|| getSecondFragment() == null
) {
761 if (listOfFiles
!= null
) { // should never be null, indeed
762 if (mDirectories
.getCount() <= 1) {
766 int levelsUp
= listOfFiles
.onBrowseUp();
767 for (int i
= 0; i
< levelsUp
&& mDirectories
.getCount() > 1; i
++) {
772 if (listOfFiles
!= null
) { // should never be null, indeed
773 setFile(listOfFiles
.getCurrentFile());
775 cleanSecondFragment();
780 protected void onSaveInstanceState(Bundle outState
) {
781 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
782 Log_OC
.e(TAG
, "onSaveInstanceState() start");
783 super.onSaveInstanceState(outState
);
784 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
785 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
786 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
787 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
789 Log_OC
.d(TAG
, "onSaveInstanceState() end");
794 protected void onResume() {
796 Log_OC
.e(TAG
, "onResume() start");
798 // refresh list of files
799 refreshListOfFilesFragment();
801 // Listen for sync messages
802 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
803 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
804 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
805 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
806 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
807 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
808 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
809 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
811 // Listen for upload messages
812 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
813 mUploadFinishReceiver
= new UploadFinishReceiver();
814 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
816 // Listen for download messages
817 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
818 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
819 mDownloadFinishReceiver
= new DownloadFinishReceiver();
820 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
822 Log_OC
.d(TAG
, "onResume() end");
827 protected void onPause() {
828 Log_OC
.e(TAG
, "onPause() start");
829 if (mSyncBroadcastReceiver
!= null
) {
830 unregisterReceiver(mSyncBroadcastReceiver
);
831 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
832 mSyncBroadcastReceiver
= null
;
834 if (mUploadFinishReceiver
!= null
) {
835 unregisterReceiver(mUploadFinishReceiver
);
836 mUploadFinishReceiver
= null
;
838 if (mDownloadFinishReceiver
!= null
) {
839 unregisterReceiver(mDownloadFinishReceiver
);
840 mDownloadFinishReceiver
= null
;
844 Log_OC
.d(TAG
, "onPause() end");
850 protected Dialog
onCreateDialog(int id
) {
851 Dialog dialog
= null
;
852 AlertDialog
.Builder builder
;
854 case DIALOG_SHORT_WAIT
: {
855 ProgressDialog working_dialog
= new ProgressDialog(this);
856 working_dialog
.setMessage(getResources().getString(
857 R
.string
.wait_a_moment
));
858 working_dialog
.setIndeterminate(true
);
859 working_dialog
.setCancelable(false
);
860 dialog
= working_dialog
;
863 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
866 String
[] allTheItems
= {getString(R
.string
.actionbar_upload_files
),
867 getString(R
.string
.actionbar_upload_from_apps
)};
869 builder
= new AlertDialog
.Builder(this);
870 builder
.setTitle(R
.string
.actionbar_upload
);
871 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
872 public void onClick(DialogInterface dialog
, int item
) {
875 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
876 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
877 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
879 // TODO create and handle new fragment
880 // LocalFileListFragment
882 } else if (item
== 1) {
883 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
884 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
885 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
886 ACTION_SELECT_CONTENT_FROM_APPS
);
890 dialog
= builder
.create();
893 case DIALOG_CERT_NOT_SAVED
: {
894 builder
= new AlertDialog
.Builder(this);
895 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
896 builder
.setCancelable(false
);
897 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
899 public void onClick(DialogInterface dialog
, int which
) {
905 dialog
= builder
.create();
916 * Translates a content URI of an image to a physical path
919 * @param uri The URI to resolve
920 * @return The path to the content or null if it could not be found
922 public String
getPath(Uri uri
) {
923 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
926 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
927 // ExternalStorageProvider
928 if (UriUtils
.isExternalStorageDocument(uri
)) {
929 final String docId
= DocumentsContract
.getDocumentId(uri
);
930 final String
[] split
= docId
.split(":");
931 final String type
= split
[0];
933 if ("primary".equalsIgnoreCase(type
)) {
934 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
938 else if (UriUtils
.isDownloadsDocument(uri
)) {
940 final String id
= DocumentsContract
.getDocumentId(uri
);
941 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
944 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, null
, null
);
947 else if (UriUtils
.isMediaDocument(uri
)) {
948 final String docId
= DocumentsContract
.getDocumentId(uri
);
949 final String
[] split
= docId
.split(":");
950 final String type
= split
[0];
952 Uri contentUri
= null
;
953 if ("image".equals(type
)) {
954 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
955 } else if ("video".equals(type
)) {
956 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
957 } else if ("audio".equals(type
)) {
958 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
961 final String selection
= "_id=?";
962 final String
[] selectionArgs
= new String
[]{split
[1]};
964 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
966 // Documents providers returned as content://...
967 else if (UriUtils
.isContentDocument(uri
)) {
968 return uri
.toString();
971 // MediaStore (and general)
972 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
974 // Return the remote address
975 if (UriUtils
.isGooglePhotosUri(uri
))
976 return uri
.getLastPathSegment();
978 return UriUtils
.getDataColumn(getApplicationContext(), uri
, null
, null
);
981 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
982 return uri
.getPath();
988 * Pushes a directory to the drop down list
990 * @param directory to push
991 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
993 public void pushDirname(OCFile directory
) {
994 if (!directory
.isFolder()) {
995 throw new IllegalArgumentException("Only directories may be pushed!");
997 mDirectories
.insert(directory
.getFileName(), 0);
1002 * Pops a directory name from the drop down list
1004 * @return True, unless the stack is empty
1006 public boolean popDirname() {
1007 mDirectories
.remove(mDirectories
.getItem(0));
1008 return !mDirectories
.isEmpty();
1011 // Custom array adapter to override text colors
1012 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1014 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1018 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1019 View v
= super.getView(position
, convertView
, parent
);
1021 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1022 android
.R
.color
.white
));
1024 fixRoot((TextView
) v
);
1028 public View
getDropDownView(int position
, View convertView
,
1030 View v
= super.getDropDownView(position
, convertView
, parent
);
1032 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1033 android
.R
.color
.white
));
1035 fixRoot((TextView
) v
);
1039 private void fixRoot(TextView v
) {
1040 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1041 v
.setText(R
.string
.default_display_name_for_root_folder
);
1047 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1050 * {@link BroadcastReceiver} to enable syncing feedback in UI
1053 public void onReceive(Context context
, Intent intent
) {
1055 String event
= intent
.getAction();
1056 Log_OC
.d(TAG
, "Received broadcast " + event
);
1057 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1058 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1059 RemoteOperationResult synchResult
= (RemoteOperationResult
) intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1060 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1064 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1065 mSyncInProgress
= true
;
1068 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1069 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1071 if (currentDir
== null
) {
1072 // current folder was removed from the server
1073 Toast
.makeText(FileDisplayActivity
.this,
1074 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1080 if (currentFile
== null
&& !getFile().isFolder()) {
1081 // currently selected file was removed in the server, and now we know it
1082 cleanSecondFragment();
1083 currentFile
= currentDir
;
1086 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1087 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1088 if (fileListFragment
!= null
) {
1089 fileListFragment
.listDirectory(currentDir
);
1092 setFile(currentFile
);
1095 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1097 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1099 /// TODO refactor and make common
1100 synchResult
!= null
&& !synchResult
.isSuccess() &&
1101 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1102 synchResult
.isIdPRedirection() ||
1103 (synchResult
.isException() && synchResult
.getException()
1104 instanceof AuthenticatorException
))) {
1106 OwnCloudClient client
= null
;
1108 OwnCloudAccount ocAccount
=
1109 new OwnCloudAccount(getAccount(), context
);
1110 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1111 removeClientFor(ocAccount
));
1112 // TODO get rid of these exceptions
1113 } catch (AccountNotFoundException e
) {
1114 e
.printStackTrace();
1115 } catch (AuthenticatorException e
) {
1116 e
.printStackTrace();
1117 } catch (OperationCanceledException e
) {
1118 e
.printStackTrace();
1119 } catch (IOException e
) {
1120 e
.printStackTrace();
1123 if (client
!= null
) {
1124 OwnCloudCredentials cred
= client
.getCredentials();
1126 AccountManager am
= AccountManager
.get(context
);
1127 if (cred
.authTokenExpires()) {
1128 am
.invalidateAuthToken(
1133 am
.clearPassword(getAccount());
1138 requestCredentialsUpdate();
1142 removeStickyBroadcast(intent
);
1143 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1144 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1146 setBackgroundText();
1150 if (synchResult
!= null
) {
1151 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1152 mLastSslUntrustedServerResult
= synchResult
;
1155 } catch (RuntimeException e
) {
1156 // avoid app crashes after changing the serial id of RemoteOperationResult
1157 // in owncloud library with broadcast notifications pending to process
1158 removeStickyBroadcast(intent
);
1164 * Show a text message on screen view for notifying user if content is
1165 * loading or folder is empty
1167 private void setBackgroundText() {
1168 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1169 if (ocFileListFragment
!= null
) {
1170 int message
= R
.string
.file_list_loading
;
1171 if (!mSyncInProgress
) {
1172 // In case file list is empty
1173 message
= R
.string
.file_list_empty
;
1175 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1177 Log_OC
.e(TAG
, "OCFileListFragment is null");
1182 * Once the file upload has finished -> update view
1184 private class UploadFinishReceiver
extends BroadcastReceiver
{
1186 * Once the file upload has finished -> update view
1188 * @author David A. Velasco
1189 * {@link BroadcastReceiver} to enable upload feedback in UI
1192 public void onReceive(Context context
, Intent intent
) {
1194 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1195 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1196 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1197 OCFile currentDir
= getCurrentDir();
1198 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1199 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1201 if (sameAccount
&& isDescendant
) {
1202 refreshListOfFilesFragment();
1205 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1206 boolean renamedInUpload
= getFile().getRemotePath().
1207 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1208 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1210 FileFragment details
= getSecondFragment();
1211 boolean detailFragmentIsShown
= (details
!= null
&&
1212 details
instanceof FileDetailFragment
);
1214 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1215 if (uploadWasFine
) {
1216 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1218 if (renamedInUpload
) {
1219 String newName
= (new File(uploadedRemotePath
)).getName();
1220 Toast msg
= Toast
.makeText(
1223 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1228 if (uploadWasFine
|| getFile().fileExists()) {
1229 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1231 cleanSecondFragment();
1234 // Force the preview if the file is an image or text file
1235 if (uploadWasFine
) {
1236 OCFile ocFile
= getFile();
1237 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1238 startImagePreview(getFile());
1239 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1240 startTextPreview(ocFile
);
1241 // TODO what about other kind of previews?
1246 if (intent
!= null
) {
1247 removeStickyBroadcast(intent
);
1257 * Class waiting for broadcast events from the {@link FileDownloader} service.
1259 * Updates the UI when a download is started or finished, provided that it is relevant for the
1262 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1264 public void onReceive(Context context
, Intent intent
) {
1266 boolean sameAccount
= isSameAccount(context
, intent
);
1267 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1268 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1270 if (sameAccount
&& isDescendant
) {
1271 refreshListOfFilesFragment();
1272 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1275 if (mWaitingToSend
!= null
) {
1276 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1277 if (mWaitingToSend
.isDown()) {
1278 sendDownloadedFile();
1283 if (intent
!= null
) {
1284 removeStickyBroadcast(intent
);
1289 private boolean isDescendant(String downloadedRemotePath
) {
1290 OCFile currentDir
= getCurrentDir();
1291 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1294 private boolean isSameAccount(Context context
, Intent intent
) {
1295 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1296 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1301 public void browseToRoot() {
1302 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1303 if (listOfFiles
!= null
) { // should never be null, indeed
1304 while (mDirectories
.getCount() > 1) {
1307 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1308 listOfFiles
.listDirectory(root
);
1309 setFile(listOfFiles
.getCurrentFile());
1310 startSyncFolderOperation(root
, false
);
1312 cleanSecondFragment();
1316 public void browseTo(OCFile folder
) {
1317 if (folder
== null
|| !folder
.isFolder()) {
1318 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1320 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1321 if (listOfFiles
!= null
) {
1322 setNavigationListWithFolder(folder
);
1323 listOfFiles
.listDirectory(folder
);
1324 setFile(listOfFiles
.getCurrentFile());
1325 startSyncFolderOperation(folder
, false
);
1327 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1329 cleanSecondFragment();
1336 * Updates action bar and second fragment, if in dual pane mode.
1339 public void onBrowsedDownTo(OCFile directory
) {
1340 pushDirname(directory
);
1341 cleanSecondFragment();
1344 startSyncFolderOperation(directory
, false
);
1349 * Shows the information of the {@link OCFile} received as a
1350 * parameter in the second fragment.
1352 * @param file {@link OCFile} whose details will be shown
1355 public void showDetails(OCFile file
) {
1356 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1357 setSecondFragment(detailFragment
);
1358 updateFragmentsVisibility(true
);
1359 updateNavigationElementsInActionBar(file
);
1367 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1368 ActionBar actionBar
= getSupportActionBar();
1369 if (chosenFile
== null
|| mDualPane
) {
1370 // only list of files - set for browsing through folders
1371 OCFile currentDir
= getCurrentDir();
1372 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1373 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1374 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1376 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1378 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1379 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1382 actionBar
.setDisplayHomeAsUpEnabled(true
);
1383 actionBar
.setDisplayShowTitleEnabled(true
);
1384 actionBar
.setTitle(chosenFile
.getFileName());
1385 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1391 protected ServiceConnection
newTransferenceServiceConnection() {
1392 return new ListServiceConnection();
1396 * Defines callbacks for service binding, passed to bindService()
1398 private class ListServiceConnection
implements ServiceConnection
{
1401 public void onServiceConnected(ComponentName component
, IBinder service
) {
1402 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1403 Log_OC
.d(TAG
, "Download service connected");
1404 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1405 if (mWaitingToPreview
!= null
)
1406 if (getStorageManager() != null
) {
1407 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1408 if (!mWaitingToPreview
.isDown()) {
1409 requestForDownload();
1413 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1414 Log_OC
.d(TAG
, "Upload service connected");
1415 mUploaderBinder
= (FileUploaderBinder
) service
;
1419 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1420 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1421 if (listOfFiles
!= null
) {
1422 listOfFiles
.listDirectory();
1424 FileFragment secondFragment
= getSecondFragment();
1425 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1426 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1427 detailFragment
.listenForTransferProgress();
1428 detailFragment
.updateFileDetails(false
, false
);
1433 public void onServiceDisconnected(ComponentName component
) {
1434 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1435 Log_OC
.d(TAG
, "Download service disconnected");
1436 mDownloaderBinder
= null
;
1437 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1438 Log_OC
.d(TAG
, "Upload service disconnected");
1439 mUploaderBinder
= null
;
1448 * Launch an intent to request the PIN code to the user before letting him use the app
1450 private void requestPinCode() {
1451 boolean pinStart
= false
;
1452 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1453 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1455 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1456 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1463 public void onSavedCertificate() {
1464 startSyncFolderOperation(getCurrentDir(), false
);
1469 public void onFailedSavingCertificate() {
1470 showDialog(DIALOG_CERT_NOT_SAVED
);
1474 public void onCancelCertificate() {
1479 * Updates the view associated to the activity after the finish of some operation over files
1480 * in the current account.
1482 * @param operation Removal operation performed.
1483 * @param result Result of the removal.
1486 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1487 super.onRemoteOperationFinish(operation
, result
);
1489 if (operation
instanceof RemoveFileOperation
) {
1490 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1492 } else if (operation
instanceof RenameFileOperation
) {
1493 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1495 } else if (operation
instanceof SynchronizeFileOperation
) {
1496 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1498 } else if (operation
instanceof CreateFolderOperation
) {
1499 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1501 } else if (operation
instanceof CreateShareOperation
) {
1502 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1504 } else if (operation
instanceof UnshareLinkOperation
) {
1505 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1507 } else if (operation
instanceof MoveFileOperation
) {
1508 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1514 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1515 if (result
.isSuccess()) {
1516 refreshShowDetails();
1517 refreshListOfFilesFragment();
1522 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1523 if (result
.isSuccess()) {
1524 refreshShowDetails();
1525 refreshListOfFilesFragment();
1527 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1528 cleanSecondFragment();
1529 refreshListOfFilesFragment();
1533 private void refreshShowDetails() {
1534 FileFragment details
= getSecondFragment();
1535 if (details
!= null
) {
1536 OCFile file
= details
.getFile();
1538 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1539 if (details
instanceof PreviewMediaFragment
) {
1540 // Refresh OCFile of the fragment
1541 ((PreviewMediaFragment
) details
).updateFile(file
);
1542 } else if (details
instanceof PreviewTextFragment
) {
1543 // Refresh OCFile of the fragment
1544 ((PreviewTextFragment
) details
).updateFile(file
);
1548 invalidateOptionsMenu();
1553 * Updates the view associated to the activity after the finish of an operation trying to remove a
1556 * @param operation Removal operation performed.
1557 * @param result Result of the removal.
1559 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1560 dismissLoadingDialog();
1562 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1566 if (result
.isSuccess()) {
1567 OCFile removedFile
= operation
.getFile();
1568 FileFragment second
= getSecondFragment();
1569 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1570 if (second
instanceof PreviewMediaFragment
) {
1571 ((PreviewMediaFragment
) second
).stopPreview(true
);
1573 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1574 cleanSecondFragment();
1576 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1577 refreshListOfFilesFragment();
1579 invalidateOptionsMenu();
1581 if (result
.isSslRecoverableException()) {
1582 mLastSslUntrustedServerResult
= result
;
1583 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1590 * Updates the view associated to the activity after the finish of an operation trying to move a
1593 * @param operation Move operation performed.
1594 * @param result Result of the move operation.
1596 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1597 if (result
.isSuccess()) {
1598 dismissLoadingDialog();
1599 refreshListOfFilesFragment();
1601 dismissLoadingDialog();
1603 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1604 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1608 } catch (NotFoundException e
) {
1609 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1616 * Updates the view associated to the activity after the finish of an operation trying to rename a
1619 * @param operation Renaming operation performed.
1620 * @param result Result of the renaming.
1622 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1623 dismissLoadingDialog();
1624 OCFile renamedFile
= operation
.getFile();
1625 if (result
.isSuccess()) {
1626 FileFragment details
= getSecondFragment();
1627 if (details
!= null
) {
1628 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile())) {
1629 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1630 showDetails(renamedFile
);
1632 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1633 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1634 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1635 int position
= ((PreviewMediaFragment
) details
).getPosition();
1636 startMediaPreview(renamedFile
, position
, true
);
1638 getFileOperationsHelper().openFile(renamedFile
);
1640 } else if (details
instanceof PreviewTextFragment
&& renamedFile
.equals(details
.getFile())) {
1641 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1642 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1643 startTextPreview(renamedFile
);
1645 getFileOperationsHelper().openFile(renamedFile
);
1650 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1651 refreshListOfFilesFragment();
1655 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1659 if (result
.isSslRecoverableException()) {
1660 mLastSslUntrustedServerResult
= result
;
1661 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1666 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1667 dismissLoadingDialog();
1668 OCFile syncedFile
= operation
.getLocalFile();
1669 if (!result
.isSuccess()) {
1670 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1671 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1672 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1673 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1679 if (operation
.transferWasRequested()) {
1680 onTransferStateChanged(syncedFile
, true
, true
);
1683 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1691 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1693 * @param operation Creation operation performed.
1694 * @param result Result of the creation.
1696 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1697 if (result
.isSuccess()) {
1698 dismissLoadingDialog();
1699 refreshListOfFilesFragment();
1701 dismissLoadingDialog();
1703 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1704 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1708 } catch (NotFoundException e
) {
1709 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1719 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1720 refreshListOfFilesFragment();
1721 FileFragment details
= getSecondFragment();
1722 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile())) {
1723 if (downloading
|| uploading
) {
1724 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1726 if (!file
.fileExists()) {
1727 cleanSecondFragment();
1729 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1737 private void requestForDownload() {
1738 Account account
= getAccount();
1739 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1740 Intent i
= new Intent(this, FileDownloader
.class);
1741 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1742 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1748 private OCFile
getCurrentDir() {
1749 OCFile file
= getFile();
1751 if (file
.isFolder()) {
1753 } else if (getStorageManager() != null
) {
1754 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1755 return getStorageManager().getFileByPath(parentPath
);
1761 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1762 long currentSyncTime
= System
.currentTimeMillis();
1764 mSyncInProgress
= true
;
1766 // perform folder synchronization
1767 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation(folder
,
1770 getFileOperationsHelper().isSharedSupported(),
1772 getStorageManager(),
1774 getApplicationContext()
1776 synchFolderOp
.execute(getAccount(), this, null
, null
);
1778 setSupportProgressBarIndeterminateVisibility(true
);
1780 setBackgroundText();
1784 * Show untrusted cert dialog
1786 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1787 // Show a dialog with the certificate info
1788 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
) result
.getException());
1789 FragmentManager fm
= getSupportFragmentManager();
1790 FragmentTransaction ft
= fm
.beginTransaction();
1791 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1794 private void requestForDownload(OCFile file
) {
1795 Account account
= getAccount();
1796 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1797 Intent i
= new Intent(this, FileDownloader
.class);
1798 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1799 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1804 private void sendDownloadedFile() {
1805 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1806 mWaitingToSend
= null
;
1811 * Requests the download of the received {@link OCFile} , updates the UI
1812 * to monitor the download progress and prepares the activity to send the file
1813 * when the download finishes.
1815 * @param file {@link OCFile} to download and preview.
1817 public void startDownloadForSending(OCFile file
) {
1818 mWaitingToSend
= file
;
1819 requestForDownload(mWaitingToSend
);
1820 boolean hasSecondFragment
= (getSecondFragment() != null
);
1821 updateFragmentsVisibility(hasSecondFragment
);
1825 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1827 * @param file Image {@link OCFile} to show.
1829 public void startImagePreview(OCFile file
) {
1830 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1831 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1832 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1833 startActivity(showDetailsIntent
);
1837 * Stars the preview of an already down media {@link OCFile}.
1839 * @param file Media {@link OCFile} to preview.
1840 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1841 * @param autoplay When 'true', the playback will start without user interactions.
1843 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1844 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1845 setSecondFragment(mediaFragment
);
1846 updateFragmentsVisibility(true
);
1847 updateNavigationElementsInActionBar(file
);
1852 * Stars the preview of a text file {@link OCFile}.
1854 * @param file Text {@link OCFile} to preview.
1856 public void startTextPreview(OCFile file
) {
1857 Bundle args
= new Bundle();
1858 args
.putParcelable(EXTRA_FILE
, file
);
1859 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1860 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(), PreviewTextFragment
.class.getName(), args
);
1861 setSecondFragment(textPreviewFragment
);
1862 updateFragmentsVisibility(true
);
1863 updateNavigationElementsInActionBar(file
);
1868 * Requests the download of the received {@link OCFile} , updates the UI
1869 * to monitor the download progress and prepares the activity to preview
1870 * or open the file when the download finishes.
1872 * @param file {@link OCFile} to download and preview.
1874 public void startDownloadForPreview(OCFile file
) {
1875 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1876 setSecondFragment(detailFragment
);
1877 mWaitingToPreview
= file
;
1878 requestForDownload();
1879 updateFragmentsVisibility(true
);
1880 updateNavigationElementsInActionBar(file
);
1885 public void cancelTransference(OCFile file
) {
1886 getFileOperationsHelper().cancelTransference(file
);
1887 if (mWaitingToPreview
!= null
&&
1888 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1889 mWaitingToPreview
= null
;
1891 if (mWaitingToSend
!= null
&&
1892 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1893 mWaitingToSend
= null
;
1895 onTransferStateChanged(file
, false
, false
);
1899 public void onRefresh(boolean ignoreETag
) {
1900 refreshList(ignoreETag
);
1904 public void onRefresh() {
1908 private void refreshList(boolean ignoreETag
) {
1909 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1910 if (listOfFiles
!= null
) {
1911 OCFile folder
= listOfFiles
.getCurrentFile();
1912 if (folder
!= null
) {
1913 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1914 listDirectory(mFile);*/
1915 startSyncFolderOperation(folder
, ignoreETag
);
1920 private void sortByDate(boolean ascending
) {
1921 getListOfFilesFragment().sortByDate(ascending
);
1924 private void sortBySize(boolean ascending
) {
1925 getListOfFilesFragment().sortBySize(ascending
);
1928 private void sortByName(boolean ascending
) {
1929 getListOfFilesFragment().sortByName(ascending
);