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
||
625 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)) {
627 final Intent fData
= data
;
628 final int fResultCode
= resultCode
;
629 getHandler().postDelayed(
633 requestMoveOperation(fData
, fResultCode
);
636 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
641 private void requestMultipleUpload(Intent data
, int resultCode
) {
642 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
643 if (filePaths
!= null
) {
644 String
[] remotePaths
= new String
[filePaths
.length
];
645 String remotePathBase
= "";
646 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
647 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
649 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
650 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
651 for (int j
= 0; j
< remotePaths
.length
; j
++) {
652 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
655 Intent i
= new Intent(this, FileUploader
.class);
656 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
657 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
658 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
659 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
660 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
661 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
665 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
666 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
673 private void requestSimpleUpload(Intent data
, int resultCode
) {
674 String filepath
= null
;
675 String mimeType
= null
;
677 Uri selectedImageUri
= data
.getData();
680 mimeType
= getContentResolver().getType(selectedImageUri
);
682 String filemanagerstring
= selectedImageUri
.getPath();
683 String selectedImagePath
= getPath(selectedImageUri
);
685 if (selectedImagePath
!= null
)
686 filepath
= selectedImagePath
;
688 filepath
= filemanagerstring
;
690 } catch (Exception e
) {
691 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
695 if (filepath
== null
) {
696 Log_OC
.e(TAG
, "Couldnt resolve path to file");
697 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
703 Intent i
= new Intent(this, FileUploader
.class);
704 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
706 String remotepath
= new String();
707 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
708 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
710 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
711 remotepath
+= OCFile
.PATH_SEPARATOR
;
713 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
715 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
716 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
719 if (cursor
!= null
&& cursor
.moveToFirst()) {
720 String displayName
= cursor
.getString(
721 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
722 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
724 displayName
.replace(File
.separatorChar
, '_');
725 displayName
.replace(File
.pathSeparatorChar
, '_');
726 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
734 remotepath
+= new File(filepath
).getName();
737 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
738 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
739 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
740 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
741 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
742 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
747 * Request the operation for moving the file/folder from one path to another
749 * @param data Intent received
750 * @param resultCode Result code received
752 private void requestMoveOperation(Intent data
, int resultCode
) {
753 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
754 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
755 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
759 public void onBackPressed() {
760 OCFileListFragment listOfFiles
= getListOfFilesFragment();
761 if (mDualPane
|| getSecondFragment() == null
) {
762 if (listOfFiles
!= null
) { // should never be null, indeed
763 if (mDirectories
.getCount() <= 1) {
767 int levelsUp
= listOfFiles
.onBrowseUp();
768 for (int i
= 0; i
< levelsUp
&& mDirectories
.getCount() > 1; i
++) {
773 if (listOfFiles
!= null
) { // should never be null, indeed
774 setFile(listOfFiles
.getCurrentFile());
776 cleanSecondFragment();
781 protected void onSaveInstanceState(Bundle outState
) {
782 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
783 Log_OC
.e(TAG
, "onSaveInstanceState() start");
784 super.onSaveInstanceState(outState
);
785 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
786 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
787 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
788 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
790 Log_OC
.d(TAG
, "onSaveInstanceState() end");
795 protected void onResume() {
797 Log_OC
.e(TAG
, "onResume() start");
799 // refresh list of files
800 refreshListOfFilesFragment();
802 // Listen for sync messages
803 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
804 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
805 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
806 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
807 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
808 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
809 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
810 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
812 // Listen for upload messages
813 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
814 mUploadFinishReceiver
= new UploadFinishReceiver();
815 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
817 // Listen for download messages
818 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
819 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
820 mDownloadFinishReceiver
= new DownloadFinishReceiver();
821 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
823 Log_OC
.d(TAG
, "onResume() end");
828 protected void onPause() {
829 Log_OC
.e(TAG
, "onPause() start");
830 if (mSyncBroadcastReceiver
!= null
) {
831 unregisterReceiver(mSyncBroadcastReceiver
);
832 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
833 mSyncBroadcastReceiver
= null
;
835 if (mUploadFinishReceiver
!= null
) {
836 unregisterReceiver(mUploadFinishReceiver
);
837 mUploadFinishReceiver
= null
;
839 if (mDownloadFinishReceiver
!= null
) {
840 unregisterReceiver(mDownloadFinishReceiver
);
841 mDownloadFinishReceiver
= null
;
845 Log_OC
.d(TAG
, "onPause() end");
851 protected Dialog
onCreateDialog(int id
) {
852 Dialog dialog
= null
;
853 AlertDialog
.Builder builder
;
855 case DIALOG_SHORT_WAIT
: {
856 ProgressDialog working_dialog
= new ProgressDialog(this);
857 working_dialog
.setMessage(getResources().getString(
858 R
.string
.wait_a_moment
));
859 working_dialog
.setIndeterminate(true
);
860 working_dialog
.setCancelable(false
);
861 dialog
= working_dialog
;
864 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
867 String
[] allTheItems
= {getString(R
.string
.actionbar_upload_files
),
868 getString(R
.string
.actionbar_upload_from_apps
)};
870 builder
= new AlertDialog
.Builder(this);
871 builder
.setTitle(R
.string
.actionbar_upload
);
872 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
873 public void onClick(DialogInterface dialog
, int item
) {
876 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
877 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
878 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
880 // TODO create and handle new fragment
881 // LocalFileListFragment
883 } else if (item
== 1) {
884 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
885 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
886 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
887 ACTION_SELECT_CONTENT_FROM_APPS
);
891 dialog
= builder
.create();
894 case DIALOG_CERT_NOT_SAVED
: {
895 builder
= new AlertDialog
.Builder(this);
896 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
897 builder
.setCancelable(false
);
898 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
900 public void onClick(DialogInterface dialog
, int which
) {
906 dialog
= builder
.create();
917 * Translates a content URI of an image to a physical path
920 * @param uri The URI to resolve
921 * @return The path to the content or null if it could not be found
923 public String
getPath(Uri uri
) {
924 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
927 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
928 // ExternalStorageProvider
929 if (UriUtils
.isExternalStorageDocument(uri
)) {
930 final String docId
= DocumentsContract
.getDocumentId(uri
);
931 final String
[] split
= docId
.split(":");
932 final String type
= split
[0];
934 if ("primary".equalsIgnoreCase(type
)) {
935 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
939 else if (UriUtils
.isDownloadsDocument(uri
)) {
941 final String id
= DocumentsContract
.getDocumentId(uri
);
942 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
945 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, null
, null
);
948 else if (UriUtils
.isMediaDocument(uri
)) {
949 final String docId
= DocumentsContract
.getDocumentId(uri
);
950 final String
[] split
= docId
.split(":");
951 final String type
= split
[0];
953 Uri contentUri
= null
;
954 if ("image".equals(type
)) {
955 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
956 } else if ("video".equals(type
)) {
957 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
958 } else if ("audio".equals(type
)) {
959 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
962 final String selection
= "_id=?";
963 final String
[] selectionArgs
= new String
[]{split
[1]};
965 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
967 // Documents providers returned as content://...
968 else if (UriUtils
.isContentDocument(uri
)) {
969 return uri
.toString();
972 // MediaStore (and general)
973 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
975 // Return the remote address
976 if (UriUtils
.isGooglePhotosUri(uri
))
977 return uri
.getLastPathSegment();
979 return UriUtils
.getDataColumn(getApplicationContext(), uri
, null
, null
);
982 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
983 return uri
.getPath();
989 * Pushes a directory to the drop down list
991 * @param directory to push
992 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
994 public void pushDirname(OCFile directory
) {
995 if (!directory
.isFolder()) {
996 throw new IllegalArgumentException("Only directories may be pushed!");
998 mDirectories
.insert(directory
.getFileName(), 0);
1003 * Pops a directory name from the drop down list
1005 * @return True, unless the stack is empty
1007 public boolean popDirname() {
1008 mDirectories
.remove(mDirectories
.getItem(0));
1009 return !mDirectories
.isEmpty();
1012 // Custom array adapter to override text colors
1013 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1015 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1019 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1020 View v
= super.getView(position
, convertView
, parent
);
1022 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1023 android
.R
.color
.white
));
1025 fixRoot((TextView
) v
);
1029 public View
getDropDownView(int position
, View convertView
,
1031 View v
= super.getDropDownView(position
, convertView
, parent
);
1033 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1034 android
.R
.color
.white
));
1036 fixRoot((TextView
) v
);
1040 private void fixRoot(TextView v
) {
1041 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1042 v
.setText(R
.string
.default_display_name_for_root_folder
);
1048 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1051 * {@link BroadcastReceiver} to enable syncing feedback in UI
1054 public void onReceive(Context context
, Intent intent
) {
1056 String event
= intent
.getAction();
1057 Log_OC
.d(TAG
, "Received broadcast " + event
);
1058 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1059 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1060 RemoteOperationResult synchResult
= (RemoteOperationResult
) intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1061 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1065 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1066 mSyncInProgress
= true
;
1069 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1070 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1072 if (currentDir
== null
) {
1073 // current folder was removed from the server
1074 Toast
.makeText(FileDisplayActivity
.this,
1075 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1081 if (currentFile
== null
&& !getFile().isFolder()) {
1082 // currently selected file was removed in the server, and now we know it
1083 cleanSecondFragment();
1084 currentFile
= currentDir
;
1087 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1088 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1089 if (fileListFragment
!= null
) {
1090 fileListFragment
.listDirectory(currentDir
);
1093 setFile(currentFile
);
1096 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1098 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1100 /// TODO refactor and make common
1101 synchResult
!= null
&& !synchResult
.isSuccess() &&
1102 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1103 synchResult
.isIdPRedirection() ||
1104 (synchResult
.isException() && synchResult
.getException()
1105 instanceof AuthenticatorException
))) {
1107 OwnCloudClient client
= null
;
1109 OwnCloudAccount ocAccount
=
1110 new OwnCloudAccount(getAccount(), context
);
1111 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1112 removeClientFor(ocAccount
));
1113 // TODO get rid of these exceptions
1114 } catch (AccountNotFoundException e
) {
1115 e
.printStackTrace();
1116 } catch (AuthenticatorException e
) {
1117 e
.printStackTrace();
1118 } catch (OperationCanceledException e
) {
1119 e
.printStackTrace();
1120 } catch (IOException e
) {
1121 e
.printStackTrace();
1124 if (client
!= null
) {
1125 OwnCloudCredentials cred
= client
.getCredentials();
1127 AccountManager am
= AccountManager
.get(context
);
1128 if (cred
.authTokenExpires()) {
1129 am
.invalidateAuthToken(
1134 am
.clearPassword(getAccount());
1139 requestCredentialsUpdate();
1143 removeStickyBroadcast(intent
);
1144 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1145 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1147 setBackgroundText();
1151 if (synchResult
!= null
) {
1152 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1153 mLastSslUntrustedServerResult
= synchResult
;
1156 } catch (RuntimeException e
) {
1157 // avoid app crashes after changing the serial id of RemoteOperationResult
1158 // in owncloud library with broadcast notifications pending to process
1159 removeStickyBroadcast(intent
);
1165 * Show a text message on screen view for notifying user if content is
1166 * loading or folder is empty
1168 private void setBackgroundText() {
1169 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1170 if (ocFileListFragment
!= null
) {
1171 int message
= R
.string
.file_list_loading
;
1172 if (!mSyncInProgress
) {
1173 // In case file list is empty
1174 message
= R
.string
.file_list_empty
;
1176 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1178 Log_OC
.e(TAG
, "OCFileListFragment is null");
1183 * Once the file upload has finished -> update view
1185 private class UploadFinishReceiver
extends BroadcastReceiver
{
1187 * Once the file upload has finished -> update view
1189 * @author David A. Velasco
1190 * {@link BroadcastReceiver} to enable upload feedback in UI
1193 public void onReceive(Context context
, Intent intent
) {
1195 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1196 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1197 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1198 OCFile currentDir
= getCurrentDir();
1199 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1200 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1202 if (sameAccount
&& isDescendant
) {
1203 refreshListOfFilesFragment();
1206 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1207 boolean renamedInUpload
= getFile().getRemotePath().
1208 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1209 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1211 FileFragment details
= getSecondFragment();
1212 boolean detailFragmentIsShown
= (details
!= null
&&
1213 details
instanceof FileDetailFragment
);
1215 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1216 if (uploadWasFine
) {
1217 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1219 if (renamedInUpload
) {
1220 String newName
= (new File(uploadedRemotePath
)).getName();
1221 Toast msg
= Toast
.makeText(
1224 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1229 if (uploadWasFine
|| getFile().fileExists()) {
1230 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1232 cleanSecondFragment();
1235 // Force the preview if the file is an image or text file
1236 if (uploadWasFine
) {
1237 OCFile ocFile
= getFile();
1238 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1239 startImagePreview(getFile());
1240 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1241 startTextPreview(ocFile
);
1242 // TODO what about other kind of previews?
1247 if (intent
!= null
) {
1248 removeStickyBroadcast(intent
);
1258 * Class waiting for broadcast events from the {@link FileDownloader} service.
1260 * Updates the UI when a download is started or finished, provided that it is relevant for the
1263 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1265 public void onReceive(Context context
, Intent intent
) {
1267 boolean sameAccount
= isSameAccount(context
, intent
);
1268 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1269 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1271 if (sameAccount
&& isDescendant
) {
1272 refreshListOfFilesFragment();
1273 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1276 if (mWaitingToSend
!= null
) {
1277 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1278 if (mWaitingToSend
.isDown()) {
1279 sendDownloadedFile();
1284 if (intent
!= null
) {
1285 removeStickyBroadcast(intent
);
1290 private boolean isDescendant(String downloadedRemotePath
) {
1291 OCFile currentDir
= getCurrentDir();
1292 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1295 private boolean isSameAccount(Context context
, Intent intent
) {
1296 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1297 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1302 public void browseToRoot() {
1303 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1304 if (listOfFiles
!= null
) { // should never be null, indeed
1305 while (mDirectories
.getCount() > 1) {
1308 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1309 listOfFiles
.listDirectory(root
);
1310 setFile(listOfFiles
.getCurrentFile());
1311 startSyncFolderOperation(root
, false
);
1313 cleanSecondFragment();
1317 public void browseTo(OCFile folder
) {
1318 if (folder
== null
|| !folder
.isFolder()) {
1319 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1321 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1322 if (listOfFiles
!= null
) {
1323 setNavigationListWithFolder(folder
);
1324 listOfFiles
.listDirectory(folder
);
1325 setFile(listOfFiles
.getCurrentFile());
1326 startSyncFolderOperation(folder
, false
);
1328 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1330 cleanSecondFragment();
1337 * Updates action bar and second fragment, if in dual pane mode.
1340 public void onBrowsedDownTo(OCFile directory
) {
1341 pushDirname(directory
);
1342 cleanSecondFragment();
1345 startSyncFolderOperation(directory
, false
);
1350 * Shows the information of the {@link OCFile} received as a
1351 * parameter in the second fragment.
1353 * @param file {@link OCFile} whose details will be shown
1356 public void showDetails(OCFile file
) {
1357 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1358 setSecondFragment(detailFragment
);
1359 updateFragmentsVisibility(true
);
1360 updateNavigationElementsInActionBar(file
);
1368 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1369 ActionBar actionBar
= getSupportActionBar();
1370 if (chosenFile
== null
|| mDualPane
) {
1371 // only list of files - set for browsing through folders
1372 OCFile currentDir
= getCurrentDir();
1373 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1374 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1375 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1377 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1379 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1380 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1383 actionBar
.setDisplayHomeAsUpEnabled(true
);
1384 actionBar
.setDisplayShowTitleEnabled(true
);
1385 actionBar
.setTitle(chosenFile
.getFileName());
1386 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1392 protected ServiceConnection
newTransferenceServiceConnection() {
1393 return new ListServiceConnection();
1397 * Defines callbacks for service binding, passed to bindService()
1399 private class ListServiceConnection
implements ServiceConnection
{
1402 public void onServiceConnected(ComponentName component
, IBinder service
) {
1403 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1404 Log_OC
.d(TAG
, "Download service connected");
1405 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1406 if (mWaitingToPreview
!= null
)
1407 if (getStorageManager() != null
) {
1408 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1409 if (!mWaitingToPreview
.isDown()) {
1410 requestForDownload();
1414 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1415 Log_OC
.d(TAG
, "Upload service connected");
1416 mUploaderBinder
= (FileUploaderBinder
) service
;
1420 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1421 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1422 if (listOfFiles
!= null
) {
1423 listOfFiles
.listDirectory();
1425 FileFragment secondFragment
= getSecondFragment();
1426 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1427 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1428 detailFragment
.listenForTransferProgress();
1429 detailFragment
.updateFileDetails(false
, false
);
1434 public void onServiceDisconnected(ComponentName component
) {
1435 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1436 Log_OC
.d(TAG
, "Download service disconnected");
1437 mDownloaderBinder
= null
;
1438 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1439 Log_OC
.d(TAG
, "Upload service disconnected");
1440 mUploaderBinder
= null
;
1449 * Launch an intent to request the PIN code to the user before letting him use the app
1451 private void requestPinCode() {
1452 boolean pinStart
= false
;
1453 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1454 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1456 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1457 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1464 public void onSavedCertificate() {
1465 startSyncFolderOperation(getCurrentDir(), false
);
1470 public void onFailedSavingCertificate() {
1471 showDialog(DIALOG_CERT_NOT_SAVED
);
1475 public void onCancelCertificate() {
1480 * Updates the view associated to the activity after the finish of some operation over files
1481 * in the current account.
1483 * @param operation Removal operation performed.
1484 * @param result Result of the removal.
1487 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1488 super.onRemoteOperationFinish(operation
, result
);
1490 if (operation
instanceof RemoveFileOperation
) {
1491 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1493 } else if (operation
instanceof RenameFileOperation
) {
1494 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1496 } else if (operation
instanceof SynchronizeFileOperation
) {
1497 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1499 } else if (operation
instanceof CreateFolderOperation
) {
1500 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1502 } else if (operation
instanceof CreateShareOperation
) {
1503 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1505 } else if (operation
instanceof UnshareLinkOperation
) {
1506 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1508 } else if (operation
instanceof MoveFileOperation
) {
1509 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1515 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1516 if (result
.isSuccess()) {
1517 refreshShowDetails();
1518 refreshListOfFilesFragment();
1523 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1524 if (result
.isSuccess()) {
1525 refreshShowDetails();
1526 refreshListOfFilesFragment();
1528 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1529 cleanSecondFragment();
1530 refreshListOfFilesFragment();
1534 private void refreshShowDetails() {
1535 FileFragment details
= getSecondFragment();
1536 if (details
!= null
) {
1537 OCFile file
= details
.getFile();
1539 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1540 if (details
instanceof PreviewMediaFragment
) {
1541 // Refresh OCFile of the fragment
1542 ((PreviewMediaFragment
) details
).updateFile(file
);
1543 } else if (details
instanceof PreviewTextFragment
) {
1544 // Refresh OCFile of the fragment
1545 ((PreviewTextFragment
) details
).updateFile(file
);
1549 invalidateOptionsMenu();
1554 * Updates the view associated to the activity after the finish of an operation trying to remove a
1557 * @param operation Removal operation performed.
1558 * @param result Result of the removal.
1560 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1561 dismissLoadingDialog();
1563 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1567 if (result
.isSuccess()) {
1568 OCFile removedFile
= operation
.getFile();
1569 FileFragment second
= getSecondFragment();
1570 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1571 if (second
instanceof PreviewMediaFragment
) {
1572 ((PreviewMediaFragment
) second
).stopPreview(true
);
1574 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1575 cleanSecondFragment();
1577 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1578 refreshListOfFilesFragment();
1580 invalidateOptionsMenu();
1582 if (result
.isSslRecoverableException()) {
1583 mLastSslUntrustedServerResult
= result
;
1584 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1591 * Updates the view associated to the activity after the finish of an operation trying to move a
1594 * @param operation Move operation performed.
1595 * @param result Result of the move operation.
1597 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1598 if (result
.isSuccess()) {
1599 dismissLoadingDialog();
1600 refreshListOfFilesFragment();
1602 dismissLoadingDialog();
1604 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1605 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1609 } catch (NotFoundException e
) {
1610 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1617 * Updates the view associated to the activity after the finish of an operation trying to rename a
1620 * @param operation Renaming operation performed.
1621 * @param result Result of the renaming.
1623 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1624 dismissLoadingDialog();
1625 OCFile renamedFile
= operation
.getFile();
1626 if (result
.isSuccess()) {
1627 FileFragment details
= getSecondFragment();
1628 if (details
!= null
) {
1629 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile())) {
1630 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1631 showDetails(renamedFile
);
1633 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1634 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1635 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1636 int position
= ((PreviewMediaFragment
) details
).getPosition();
1637 startMediaPreview(renamedFile
, position
, true
);
1639 getFileOperationsHelper().openFile(renamedFile
);
1641 } else if (details
instanceof PreviewTextFragment
&& renamedFile
.equals(details
.getFile())) {
1642 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1643 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1644 startTextPreview(renamedFile
);
1646 getFileOperationsHelper().openFile(renamedFile
);
1651 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1652 refreshListOfFilesFragment();
1656 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1660 if (result
.isSslRecoverableException()) {
1661 mLastSslUntrustedServerResult
= result
;
1662 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1667 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1668 dismissLoadingDialog();
1669 OCFile syncedFile
= operation
.getLocalFile();
1670 if (!result
.isSuccess()) {
1671 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1672 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1673 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1674 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1680 if (operation
.transferWasRequested()) {
1681 onTransferStateChanged(syncedFile
, true
, true
);
1684 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1692 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1694 * @param operation Creation operation performed.
1695 * @param result Result of the creation.
1697 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1698 if (result
.isSuccess()) {
1699 dismissLoadingDialog();
1700 refreshListOfFilesFragment();
1702 dismissLoadingDialog();
1704 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1705 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1709 } catch (NotFoundException e
) {
1710 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1720 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1721 refreshListOfFilesFragment();
1722 FileFragment details
= getSecondFragment();
1723 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile())) {
1724 if (downloading
|| uploading
) {
1725 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1727 if (!file
.fileExists()) {
1728 cleanSecondFragment();
1730 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1738 private void requestForDownload() {
1739 Account account
= getAccount();
1740 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1741 Intent i
= new Intent(this, FileDownloader
.class);
1742 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1743 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1749 private OCFile
getCurrentDir() {
1750 OCFile file
= getFile();
1752 if (file
.isFolder()) {
1754 } else if (getStorageManager() != null
) {
1755 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1756 return getStorageManager().getFileByPath(parentPath
);
1762 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1763 long currentSyncTime
= System
.currentTimeMillis();
1765 mSyncInProgress
= true
;
1767 // perform folder synchronization
1768 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation(folder
,
1771 getFileOperationsHelper().isSharedSupported(),
1773 getStorageManager(),
1775 getApplicationContext()
1777 synchFolderOp
.execute(getAccount(), this, null
, null
);
1779 setSupportProgressBarIndeterminateVisibility(true
);
1781 setBackgroundText();
1785 * Show untrusted cert dialog
1787 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1788 // Show a dialog with the certificate info
1789 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
) result
.getException());
1790 FragmentManager fm
= getSupportFragmentManager();
1791 FragmentTransaction ft
= fm
.beginTransaction();
1792 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1795 private void requestForDownload(OCFile file
) {
1796 Account account
= getAccount();
1797 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1798 Intent i
= new Intent(this, FileDownloader
.class);
1799 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1800 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1805 private void sendDownloadedFile() {
1806 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1807 mWaitingToSend
= null
;
1812 * Requests the download of the received {@link OCFile} , updates the UI
1813 * to monitor the download progress and prepares the activity to send the file
1814 * when the download finishes.
1816 * @param file {@link OCFile} to download and preview.
1818 public void startDownloadForSending(OCFile file
) {
1819 mWaitingToSend
= file
;
1820 requestForDownload(mWaitingToSend
);
1821 boolean hasSecondFragment
= (getSecondFragment() != null
);
1822 updateFragmentsVisibility(hasSecondFragment
);
1826 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1828 * @param file Image {@link OCFile} to show.
1830 public void startImagePreview(OCFile file
) {
1831 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1832 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1833 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1834 startActivity(showDetailsIntent
);
1838 * Stars the preview of an already down media {@link OCFile}.
1840 * @param file Media {@link OCFile} to preview.
1841 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1842 * @param autoplay When 'true', the playback will start without user interactions.
1844 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1845 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1846 setSecondFragment(mediaFragment
);
1847 updateFragmentsVisibility(true
);
1848 updateNavigationElementsInActionBar(file
);
1853 * Stars the preview of a text file {@link OCFile}.
1855 * @param file Text {@link OCFile} to preview.
1857 public void startTextPreview(OCFile file
) {
1858 Bundle args
= new Bundle();
1859 args
.putParcelable(EXTRA_FILE
, file
);
1860 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1861 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(), PreviewTextFragment
.class.getName(), args
);
1862 setSecondFragment(textPreviewFragment
);
1863 updateFragmentsVisibility(true
);
1864 updateNavigationElementsInActionBar(file
);
1869 * Requests the download of the received {@link OCFile} , updates the UI
1870 * to monitor the download progress and prepares the activity to preview
1871 * or open the file when the download finishes.
1873 * @param file {@link OCFile} to download and preview.
1875 public void startDownloadForPreview(OCFile file
) {
1876 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1877 setSecondFragment(detailFragment
);
1878 mWaitingToPreview
= file
;
1879 requestForDownload();
1880 updateFragmentsVisibility(true
);
1881 updateNavigationElementsInActionBar(file
);
1886 public void cancelTransference(OCFile file
) {
1887 getFileOperationsHelper().cancelTransference(file
);
1888 if (mWaitingToPreview
!= null
&&
1889 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1890 mWaitingToPreview
= null
;
1892 if (mWaitingToSend
!= null
&&
1893 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1894 mWaitingToSend
= null
;
1896 onTransferStateChanged(file
, false
, false
);
1900 public void onRefresh(boolean ignoreETag
) {
1901 refreshList(ignoreETag
);
1905 public void onRefresh() {
1909 private void refreshList(boolean ignoreETag
) {
1910 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1911 if (listOfFiles
!= null
) {
1912 OCFile folder
= listOfFiles
.getCurrentFile();
1913 if (folder
!= null
) {
1914 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1915 listDirectory(mFile);*/
1916 startSyncFolderOperation(folder
, ignoreETag
);
1921 private void sortByDate(boolean ascending
) {
1922 getListOfFilesFragment().sortByDate(ascending
);
1925 private void sortBySize(boolean ascending
) {
1926 getListOfFilesFragment().sortBySize(ascending
);
1929 private void sortByName(boolean ascending
) {
1930 getListOfFilesFragment().sortByName(ascending
);