1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
21 import android
.accounts
.Account
;
22 import android
.accounts
.AccountManager
;
23 import android
.accounts
.AuthenticatorException
;
24 import android
.accounts
.OperationCanceledException
;
25 import android
.app
.AlertDialog
;
26 import android
.app
.Dialog
;
27 import android
.app
.ProgressDialog
;
28 import android
.content
.BroadcastReceiver
;
29 import android
.content
.ComponentName
;
30 import android
.content
.ContentResolver
;
31 import android
.content
.Context
;
32 import android
.content
.DialogInterface
;
33 import android
.content
.Intent
;
34 import android
.content
.IntentFilter
;
35 import android
.content
.ServiceConnection
;
36 import android
.content
.SharedPreferences
;
37 import android
.content
.SyncRequest
;
38 import android
.content
.res
.Resources
.NotFoundException
;
39 import android
.database
.Cursor
;
40 import android
.net
.Uri
;
41 import android
.os
.Bundle
;
42 import android
.os
.IBinder
;
43 import android
.preference
.PreferenceManager
;
44 import android
.provider
.MediaStore
;
45 import android
.support
.v4
.app
.Fragment
;
46 import android
.support
.v4
.app
.FragmentManager
;
47 import android
.support
.v4
.app
.FragmentTransaction
;
48 import android
.view
.View
;
49 import android
.view
.ViewGroup
;
50 import android
.widget
.ArrayAdapter
;
51 import android
.widget
.TextView
;
52 import android
.widget
.Toast
;
54 import com
.actionbarsherlock
.app
.ActionBar
;
55 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
56 import com
.actionbarsherlock
.view
.Menu
;
57 import com
.actionbarsherlock
.view
.MenuInflater
;
58 import com
.actionbarsherlock
.view
.MenuItem
;
59 import com
.actionbarsherlock
.view
.Window
;
60 import com
.owncloud
.android
.BuildConfig
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
68 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
69 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
72 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
73 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
77 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
78 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
79 import com
.owncloud
.android
.operations
.CreateShareOperation
;
80 import com
.owncloud
.android
.operations
.MoveFileOperation
;
81 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
82 import com
.owncloud
.android
.operations
.RenameFileOperation
;
83 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
84 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
85 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
86 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
87 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
88 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
89 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
91 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
92 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
94 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
99 import com
.owncloud
.android
.utils
.DisplayUtils
;
100 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
103 import java
.io
.IOException
;
107 * Displays, what files the user has available in his ownCloud.
109 * @author Bartek Przybylski
110 * @author David A. Velasco
113 public class FileDisplayActivity
extends HookActivity
implements
114 FileFragment
.ContainerActivity
, OnNavigationListener
,
115 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
117 private ArrayAdapter
<String
> mDirectories
;
119 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
120 private UploadFinishReceiver mUploadFinishReceiver
;
121 private DownloadFinishReceiver mDownloadFinishReceiver
;
122 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
124 private boolean mDualPane
;
125 private View mLeftFragmentContainer
;
126 private View mRightFragmentContainer
;
128 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
129 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
130 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
132 public static final int DIALOG_SHORT_WAIT
= 0;
133 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
134 private static final int DIALOG_CERT_NOT_SAVED
= 2;
136 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
138 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
139 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
140 public static final int ACTION_MOVE_FILES
= 3;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private String DIALOG_UNTRUSTED_CERT
;
153 private OCFile mWaitingToSend
;
156 protected void onCreate(Bundle savedInstanceState
) {
157 Log_OC
.d(TAG
, "onCreate() start");
158 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
160 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
162 // PIN CODE request ; best location is to decide, let's try this first
163 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
165 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
169 /// grant that FileObserverService is watching favourite files
170 if (savedInstanceState
== null
) {
171 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
172 startService(initObserversIntent
);
175 /// Load of saved instance state
176 if (savedInstanceState
!= null
) {
177 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
178 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
179 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
182 mWaitingToPreview
= null
;
183 mSyncInProgress
= false
;
184 mWaitingToSend
= null
;
189 // Inflate and set the layout view
190 setContentView(R
.layout
.files
);
191 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
192 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
193 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
194 if (savedInstanceState
== null
) {
195 createMinFragments();
199 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
200 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
201 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
205 Log_OC
.d(TAG
, "onCreate() end");
209 protected void onStart() {
211 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 protected void onDestroy() {
220 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
223 protected void onAccountSet(boolean stateWasRecovered
) {
224 super.onAccountSet(stateWasRecovered
);
225 if (getAccount() != null
) {
226 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
227 OCFile file
= getFile();
228 // get parent from path
229 String parentPath
= "";
231 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
232 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
233 // get parent from path
234 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
235 if (getStorageManager().getFileByPath(parentPath
) == null
)
236 file
= null
; // not able to know the directory where the file is uploading
238 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
242 // fall back to root folder
243 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
246 setNavigationListWithFolder(file
);
248 if (!stateWasRecovered
) {
249 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
250 initFragmentsWithFile();
251 if (file
.isFolder()) {
252 startSyncFolderOperation(file
, false
);
256 updateFragmentsVisibility(!file
.isFolder());
257 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
263 private void setNavigationListWithFolder(OCFile file
) {
264 mDirectories
.clear();
265 OCFile fileIt
= file
;
267 while (fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
268 if (fileIt
.isFolder()) {
269 mDirectories
.add(fileIt
.getFileName());
271 // get parent from path
272 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
273 fileIt
= getStorageManager().getFileByPath(parentPath
);
275 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
279 private void createMinFragments() {
280 OCFileListFragment listOfFiles
= new OCFileListFragment();
281 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
282 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
283 transaction
.commit();
286 private void initFragmentsWithFile() {
287 if (getAccount() != null
&& getFile() != null
) {
289 OCFileListFragment listOfFiles
= getListOfFilesFragment();
290 if (listOfFiles
!= null
) {
291 listOfFiles
.listDirectory(getCurrentDir());
293 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
297 OCFile file
= getFile();
298 Fragment secondFragment
= chooseInitialSecondFragment(file
);
299 if (secondFragment
!= null
) {
300 setSecondFragment(secondFragment
);
301 updateFragmentsVisibility(true
);
302 updateNavigationElementsInActionBar(file
);
305 cleanSecondFragment();
306 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
307 startTextPreview(file
);
311 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
312 if (getAccount() == null
) {
313 Log_OC
.wtf(TAG
, "\t account is NULL");
315 if (getFile() == null
) {
316 Log_OC
.wtf(TAG
, "\t file is NULL");
321 private Fragment
chooseInitialSecondFragment(OCFile file
) {
322 Fragment secondFragment
= null
;
323 if (file
!= null
&& !file
.isFolder()) {
324 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
325 && file
.getLastSyncDateForProperties() > 0 // temporal fix
327 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
328 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
329 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
331 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
332 secondFragment
= null
;
333 } else secondFragment
= new FileDetailFragment(file
, getAccount());
335 return secondFragment
;
340 * Replaces the second fragment managed by the activity with the received as
343 * Assumes never will be more than two fragments managed at the same time.
345 * @param fragment New second Fragment to set.
347 private void setSecondFragment(Fragment fragment
) {
348 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
349 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
350 transaction
.commit();
354 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
356 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
357 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
359 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
360 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
363 } else if (existsSecondFragment
) {
364 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
365 mLeftFragmentContainer
.setVisibility(View
.GONE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
372 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
373 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
376 mRightFragmentContainer
.setVisibility(View
.GONE
);
382 private OCFileListFragment
getListOfFilesFragment() {
383 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
384 if (listOfFiles
!= null
) {
385 return (OCFileListFragment
) listOfFiles
;
387 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
391 public FileFragment
getSecondFragment() {
392 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
393 if (second
!= null
) {
394 return (FileFragment
) second
;
399 protected void cleanSecondFragment() {
400 Fragment second
= getSecondFragment();
401 if (second
!= null
) {
402 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
406 updateFragmentsVisibility(false
);
407 updateNavigationElementsInActionBar(null
);
410 protected void refreshListOfFilesFragment() {
411 OCFileListFragment fileListFragment
= getListOfFilesFragment();
412 if (fileListFragment
!= null
) {
413 fileListFragment
.listDirectory();
417 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
418 FileFragment secondFragment
= getSecondFragment();
419 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
420 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
421 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
422 OCFile fileInFragment
= detailsFragment
.getFile();
423 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
424 // the user browsed to other file ; forget the automatic preview
425 mWaitingToPreview
= null
;
427 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
428 // grant that the right panel updates the progress bar
429 detailsFragment
.listenForTransferProgress();
430 detailsFragment
.updateFileDetails(true
, false
);
432 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
433 // update the right panel
434 boolean detailsFragmentChanged
= false
;
437 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
438 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
439 startMediaPreview(mWaitingToPreview
, 0, true
);
440 detailsFragmentChanged
= true
;
441 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
442 startTextPreview(mWaitingToPreview
);
443 detailsFragmentChanged
= true
;
445 getFileOperationsHelper().openFile(mWaitingToPreview
);
448 mWaitingToPreview
= null
;
450 if (!detailsFragmentChanged
) {
451 detailsFragment
.updateFileDetails(false
, (success
));
458 public boolean onPrepareOptionsMenu(Menu menu
) {
459 if (BuildConfig
.DEBUG
) {
460 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
462 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
464 return super.onPrepareOptionsMenu(menu
);
468 public boolean onCreateOptionsMenu(Menu menu
) {
469 MenuInflater inflater
= getSherlock().getMenuInflater();
470 inflater
.inflate(R
.menu
.main_menu
, menu
);
475 public boolean onOptionsItemSelected(MenuItem item
) {
476 boolean retval
= true
;
477 switch (item
.getItemId()) {
478 case R
.id
.action_create_dir
: {
479 CreateFolderDialogFragment dialog
=
480 CreateFolderDialogFragment
.newInstance(getCurrentDir());
481 dialog
.show(getSupportFragmentManager(), "createdirdialog");
484 case R
.id
.action_sync_account
: {
485 startSynchronization();
488 case R
.id
.action_upload
: {
489 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
492 case R
.id
.action_settings
: {
493 Intent settingsIntent
= new Intent(this, Preferences
.class);
494 startActivity(settingsIntent
);
497 case R
.id
.action_logger
: {
498 Intent loggerIntent
= new Intent(getApplicationContext(), LogHistoryActivity
.class);
499 startActivity(loggerIntent
);
502 case android
.R
.id
.home
: {
503 FileFragment second
= getSecondFragment();
504 OCFile currentDir
= getCurrentDir();
505 if ((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
506 (second
!= null
&& second
.getFile() != null
)) {
513 retval
= super.onOptionsItemSelected(item
);
518 private void startSynchronization() {
519 Log_OC
.e(TAG
, "Got to start sync");
520 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
521 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
522 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
523 Bundle bundle
= new Bundle();
524 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
525 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
526 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
527 ContentResolver
.requestSync(
529 MainApp
.getAuthority(), bundle
);
531 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
532 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
533 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
534 builder
.setExpedited(true
);
535 builder
.setManual(true
);
537 SyncRequest request
= builder
.build();
538 ContentResolver
.requestSync(request
);
544 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
545 if (itemPosition
!= 0) {
546 String targetPath
= "";
547 for (int i
= itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
548 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
550 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
551 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
552 if (targetFolder
!= null
) {
553 browseTo(targetFolder
);
556 // the next operation triggers a new call to this method, but it's necessary to
557 // ensure that the name exposed in the action bar is the current directory when the
558 // user selected it in the navigation list
559 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
560 getSupportActionBar().setSelectedNavigationItem(0);
566 * Called, when the user selected something for uploading
568 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
569 super.onActivityResult(requestCode
, resultCode
, data
);
571 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
572 requestSimpleUpload(data
, resultCode
);
574 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
575 requestMultipleUpload(data
, resultCode
);
577 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
578 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)) {
580 final Intent fData
= data
;
581 final int fResultCode
= resultCode
;
582 getHandler().postDelayed(
586 requestMoveOperation(fData
, fResultCode
);
589 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
594 private void requestMultipleUpload(Intent data
, int resultCode
) {
595 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
596 if (filePaths
!= null
) {
597 String
[] remotePaths
= new String
[filePaths
.length
];
598 String remotePathBase
= "";
599 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
600 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
602 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
603 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
604 for (int j
= 0; j
< remotePaths
.length
; j
++) {
605 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
608 Intent i
= new Intent(this, FileUploader
.class);
609 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
610 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
611 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
612 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
613 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
614 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
618 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
619 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
626 private void requestSimpleUpload(Intent data
, int resultCode
) {
627 String filepath
= null
;
629 Uri selectedImageUri
= data
.getData();
631 String filemanagerstring
= selectedImageUri
.getPath();
632 String selectedImagePath
= getPath(selectedImageUri
);
634 if (selectedImagePath
!= null
)
635 filepath
= selectedImagePath
;
637 filepath
= filemanagerstring
;
639 } catch (Exception e
) {
640 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
644 if (filepath
== null
) {
645 Log_OC
.e(TAG
, "Couldnt resolve path to file");
646 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
652 Intent i
= new Intent(this, FileUploader
.class);
653 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
655 String remotepath
= new String();
656 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
657 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
659 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
660 remotepath
+= OCFile
.PATH_SEPARATOR
;
661 remotepath
+= new File(filepath
).getName();
663 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
664 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
665 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
666 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
667 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
672 * Request the operation for moving the file/folder from one path to another
674 * @param data Intent received
675 * @param resultCode Result code received
677 private void requestMoveOperation(Intent data
, int resultCode
) {
678 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
679 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
680 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
684 public void onBackPressed() {
685 OCFileListFragment listOfFiles
= getListOfFilesFragment();
686 if (mDualPane
|| getSecondFragment() == null
) {
687 if (listOfFiles
!= null
) { // should never be null, indeed
688 if (mDirectories
.getCount() <= 1) {
692 int levelsUp
= listOfFiles
.onBrowseUp();
693 for (int i
= 0; i
< levelsUp
&& mDirectories
.getCount() > 1; i
++) {
698 if (listOfFiles
!= null
) { // should never be null, indeed
699 setFile(listOfFiles
.getCurrentFile());
701 cleanSecondFragment();
706 protected void onSaveInstanceState(Bundle outState
) {
707 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
708 Log_OC
.e(TAG
, "onSaveInstanceState() start");
709 super.onSaveInstanceState(outState
);
710 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
711 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
712 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
713 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
715 Log_OC
.d(TAG
, "onSaveInstanceState() end");
720 protected void onResume() {
722 Log_OC
.e(TAG
, "onResume() start");
724 // refresh list of files
725 refreshListOfFilesFragment();
727 // Listen for sync messages
728 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
729 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
730 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
731 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
732 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
733 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
734 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
735 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
737 // Listen for upload messages
738 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
739 mUploadFinishReceiver
= new UploadFinishReceiver();
740 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
742 // Listen for download messages
743 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
744 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
745 mDownloadFinishReceiver
= new DownloadFinishReceiver();
746 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
748 Log_OC
.d(TAG
, "onResume() end");
753 protected void onPause() {
754 Log_OC
.e(TAG
, "onPause() start");
755 if (mSyncBroadcastReceiver
!= null
) {
756 unregisterReceiver(mSyncBroadcastReceiver
);
757 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
758 mSyncBroadcastReceiver
= null
;
760 if (mUploadFinishReceiver
!= null
) {
761 unregisterReceiver(mUploadFinishReceiver
);
762 mUploadFinishReceiver
= null
;
764 if (mDownloadFinishReceiver
!= null
) {
765 unregisterReceiver(mDownloadFinishReceiver
);
766 mDownloadFinishReceiver
= null
;
770 Log_OC
.d(TAG
, "onPause() end");
776 protected Dialog
onCreateDialog(int id
) {
777 Dialog dialog
= null
;
778 AlertDialog
.Builder builder
;
780 case DIALOG_SHORT_WAIT
: {
781 ProgressDialog working_dialog
= new ProgressDialog(this);
782 working_dialog
.setMessage(getResources().getString(
783 R
.string
.wait_a_moment
));
784 working_dialog
.setIndeterminate(true
);
785 working_dialog
.setCancelable(false
);
786 dialog
= working_dialog
;
789 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
792 String
[] allTheItems
= {getString(R
.string
.actionbar_upload_files
),
793 getString(R
.string
.actionbar_upload_from_apps
)};
795 builder
= new AlertDialog
.Builder(this);
796 builder
.setTitle(R
.string
.actionbar_upload
);
797 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
798 public void onClick(DialogInterface dialog
, int item
) {
801 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
802 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
803 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
805 // TODO create and handle new fragment
806 // LocalFileListFragment
808 } else if (item
== 1) {
809 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
810 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
811 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
812 ACTION_SELECT_CONTENT_FROM_APPS
);
816 dialog
= builder
.create();
819 case DIALOG_CERT_NOT_SAVED
: {
820 builder
= new AlertDialog
.Builder(this);
821 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
822 builder
.setCancelable(false
);
823 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
825 public void onClick(DialogInterface dialog
, int which
) {
831 dialog
= builder
.create();
843 * Translates a content URI of an image to a physical path
846 * @param uri The URI to resolve
847 * @return The path to the image or null if it could not be found
849 public String
getPath(Uri uri
) {
850 String
[] projection
= {MediaStore
.Images
.Media
.DATA
};
851 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
852 if (cursor
!= null
) {
853 int column_index
= cursor
854 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
855 cursor
.moveToFirst();
856 return cursor
.getString(column_index
);
862 * Pushes a directory to the drop down list
864 * @param directory to push
865 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
867 public void pushDirname(OCFile directory
) {
868 if (!directory
.isFolder()) {
869 throw new IllegalArgumentException("Only directories may be pushed!");
871 mDirectories
.insert(directory
.getFileName(), 0);
876 * Pops a directory name from the drop down list
878 * @return True, unless the stack is empty
880 public boolean popDirname() {
881 mDirectories
.remove(mDirectories
.getItem(0));
882 return !mDirectories
.isEmpty();
885 // Custom array adapter to override text colors
886 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
888 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
892 public View
getView(int position
, View convertView
, ViewGroup parent
) {
893 View v
= super.getView(position
, convertView
, parent
);
895 ((TextView
) v
).setTextColor(getResources().getColorStateList(
896 android
.R
.color
.white
));
898 fixRoot((TextView
) v
);
902 public View
getDropDownView(int position
, View convertView
,
904 View v
= super.getDropDownView(position
, convertView
, parent
);
906 ((TextView
) v
).setTextColor(getResources().getColorStateList(
907 android
.R
.color
.white
));
909 fixRoot((TextView
) v
);
913 private void fixRoot(TextView v
) {
914 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
915 v
.setText(R
.string
.default_display_name_for_root_folder
);
921 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
924 * {@link BroadcastReceiver} to enable syncing feedback in UI
927 public void onReceive(Context context
, Intent intent
) {
929 String event
= intent
.getAction();
930 Log_OC
.d(TAG
, "Received broadcast " + event
);
931 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
932 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
933 RemoteOperationResult synchResult
= (RemoteOperationResult
) intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
934 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
938 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
939 mSyncInProgress
= true
;
942 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
943 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
945 if (currentDir
== null
) {
946 // current folder was removed from the server
947 Toast
.makeText(FileDisplayActivity
.this,
948 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
954 if (currentFile
== null
&& !getFile().isFolder()) {
955 // currently selected file was removed in the server, and now we know it
956 cleanSecondFragment();
957 currentFile
= currentDir
;
960 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
961 OCFileListFragment fileListFragment
= getListOfFilesFragment();
962 if (fileListFragment
!= null
) {
963 fileListFragment
.listDirectory(currentDir
);
966 setFile(currentFile
);
969 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
971 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
973 /// TODO refactor and make common
974 synchResult
!= null
&& !synchResult
.isSuccess() &&
975 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
976 synchResult
.isIdPRedirection() ||
977 (synchResult
.isException() && synchResult
.getException()
978 instanceof AuthenticatorException
))) {
980 OwnCloudClient client
= null
;
982 OwnCloudAccount ocAccount
=
983 new OwnCloudAccount(getAccount(), context
);
984 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
985 removeClientFor(ocAccount
));
986 // TODO get rid of these exceptions
987 } catch (AccountNotFoundException e
) {
989 } catch (AuthenticatorException e
) {
991 } catch (OperationCanceledException e
) {
993 } catch (IOException e
) {
997 if (client
!= null
) {
998 OwnCloudCredentials cred
= client
.getCredentials();
1000 AccountManager am
= AccountManager
.get(context
);
1001 if (cred
.authTokenExpires()) {
1002 am
.invalidateAuthToken(
1007 am
.clearPassword(getAccount());
1012 requestCredentialsUpdate();
1016 removeStickyBroadcast(intent
);
1017 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1018 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1020 setBackgroundText();
1024 if (synchResult
!= null
) {
1025 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1026 mLastSslUntrustedServerResult
= synchResult
;
1029 } catch (RuntimeException e
) {
1030 // avoid app crashes after changing the serial id of RemoteOperationResult
1031 // in owncloud library with broadcast notifications pending to process
1032 removeStickyBroadcast(intent
);
1038 * Show a text message on screen view for notifying user if content is
1039 * loading or folder is empty
1041 private void setBackgroundText() {
1042 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1043 if (ocFileListFragment
!= null
) {
1044 int message
= R
.string
.file_list_loading
;
1045 if (!mSyncInProgress
) {
1046 // In case file list is empty
1047 message
= R
.string
.file_list_empty
;
1049 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1051 Log_OC
.e(TAG
, "OCFileListFragment is null");
1056 * Once the file upload has finished -> update view
1058 private class UploadFinishReceiver
extends BroadcastReceiver
{
1060 * Once the file upload has finished -> update view
1062 * @author David A. Velasco
1063 * {@link BroadcastReceiver} to enable upload feedback in UI
1066 public void onReceive(Context context
, Intent intent
) {
1068 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1069 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1070 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1071 OCFile currentDir
= getCurrentDir();
1072 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1073 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1075 if (sameAccount
&& isDescendant
) {
1076 refreshListOfFilesFragment();
1079 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1080 boolean renamedInUpload
= getFile().getRemotePath().
1081 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1082 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1084 FileFragment details
= getSecondFragment();
1085 boolean detailFragmentIsShown
= (details
!= null
&&
1086 details
instanceof FileDetailFragment
);
1088 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1089 if (uploadWasFine
) {
1090 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1092 if (renamedInUpload
) {
1093 String newName
= (new File(uploadedRemotePath
)).getName();
1094 Toast msg
= Toast
.makeText(
1097 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1102 if (uploadWasFine
|| getFile().fileExists()) {
1103 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1105 cleanSecondFragment();
1108 // Force the preview if the file is an image or text file
1109 if (uploadWasFine
) {
1110 OCFile ocFile
= getFile();
1111 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1112 startImagePreview(getFile());
1113 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1114 startTextPreview(ocFile
);
1115 // TODO what about other kind of previews?
1120 if (intent
!= null
) {
1121 removeStickyBroadcast(intent
);
1131 * Class waiting for broadcast events from the {@link FileDownloader} service.
1133 * Updates the UI when a download is started or finished, provided that it is relevant for the
1136 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1138 public void onReceive(Context context
, Intent intent
) {
1140 boolean sameAccount
= isSameAccount(context
, intent
);
1141 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1142 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1144 if (sameAccount
&& isDescendant
) {
1145 refreshListOfFilesFragment();
1146 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1149 if (mWaitingToSend
!= null
) {
1150 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1151 if (mWaitingToSend
.isDown()) {
1152 sendDownloadedFile();
1157 if (intent
!= null
) {
1158 removeStickyBroadcast(intent
);
1163 private boolean isDescendant(String downloadedRemotePath
) {
1164 OCFile currentDir
= getCurrentDir();
1165 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1168 private boolean isSameAccount(Context context
, Intent intent
) {
1169 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1170 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1175 public void browseToRoot() {
1176 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1177 if (listOfFiles
!= null
) { // should never be null, indeed
1178 while (mDirectories
.getCount() > 1) {
1181 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1182 listOfFiles
.listDirectory(root
);
1183 setFile(listOfFiles
.getCurrentFile());
1184 startSyncFolderOperation(root
, false
);
1186 cleanSecondFragment();
1190 public void browseTo(OCFile folder
) {
1191 if (folder
== null
|| !folder
.isFolder()) {
1192 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1194 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1195 if (listOfFiles
!= null
) {
1196 setNavigationListWithFolder(folder
);
1197 listOfFiles
.listDirectory(folder
);
1198 setFile(listOfFiles
.getCurrentFile());
1199 startSyncFolderOperation(folder
, false
);
1201 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1203 cleanSecondFragment();
1210 * Updates action bar and second fragment, if in dual pane mode.
1213 public void onBrowsedDownTo(OCFile directory
) {
1214 pushDirname(directory
);
1215 cleanSecondFragment();
1218 startSyncFolderOperation(directory
, false
);
1223 * Shows the information of the {@link OCFile} received as a
1224 * parameter in the second fragment.
1226 * @param file {@link OCFile} whose details will be shown
1229 public void showDetails(OCFile file
) {
1230 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1231 setSecondFragment(detailFragment
);
1232 updateFragmentsVisibility(true
);
1233 updateNavigationElementsInActionBar(file
);
1241 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1242 ActionBar actionBar
= getSupportActionBar();
1243 if (chosenFile
== null
|| mDualPane
) {
1244 // only list of files - set for browsing through folders
1245 OCFile currentDir
= getCurrentDir();
1246 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1247 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1248 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1250 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1252 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1253 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1256 actionBar
.setDisplayHomeAsUpEnabled(true
);
1257 actionBar
.setDisplayShowTitleEnabled(true
);
1258 actionBar
.setTitle(chosenFile
.getFileName());
1259 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1265 protected ServiceConnection
newTransferenceServiceConnection() {
1266 return new ListServiceConnection();
1270 * Defines callbacks for service binding, passed to bindService()
1272 private class ListServiceConnection
implements ServiceConnection
{
1275 public void onServiceConnected(ComponentName component
, IBinder service
) {
1276 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1277 Log_OC
.d(TAG
, "Download service connected");
1278 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1279 if (mWaitingToPreview
!= null
)
1280 if (getStorageManager() != null
) {
1281 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1282 if (!mWaitingToPreview
.isDown()) {
1283 requestForDownload();
1287 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1288 Log_OC
.d(TAG
, "Upload service connected");
1289 mUploaderBinder
= (FileUploaderBinder
) service
;
1293 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1294 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1295 if (listOfFiles
!= null
) {
1296 listOfFiles
.listDirectory();
1298 FileFragment secondFragment
= getSecondFragment();
1299 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1300 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1301 detailFragment
.listenForTransferProgress();
1302 detailFragment
.updateFileDetails(false
, false
);
1307 public void onServiceDisconnected(ComponentName component
) {
1308 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1309 Log_OC
.d(TAG
, "Download service disconnected");
1310 mDownloaderBinder
= null
;
1311 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1312 Log_OC
.d(TAG
, "Upload service disconnected");
1313 mUploaderBinder
= null
;
1322 * Launch an intent to request the PIN code to the user before letting him use the app
1324 private void requestPinCode() {
1325 boolean pinStart
= false
;
1326 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1327 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1329 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1330 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1337 public void onSavedCertificate() {
1338 startSyncFolderOperation(getCurrentDir(), false
);
1343 public void onFailedSavingCertificate() {
1344 showDialog(DIALOG_CERT_NOT_SAVED
);
1348 public void onCancelCertificate() {
1353 * Updates the view associated to the activity after the finish of some operation over files
1354 * in the current account.
1356 * @param operation Removal operation performed.
1357 * @param result Result of the removal.
1360 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1361 super.onRemoteOperationFinish(operation
, result
);
1363 if (operation
instanceof RemoveFileOperation
) {
1364 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1366 } else if (operation
instanceof RenameFileOperation
) {
1367 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1369 } else if (operation
instanceof SynchronizeFileOperation
) {
1370 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1372 } else if (operation
instanceof CreateFolderOperation
) {
1373 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1375 } else if (operation
instanceof CreateShareOperation
) {
1376 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1378 } else if (operation
instanceof UnshareLinkOperation
) {
1379 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1381 } else if (operation
instanceof MoveFileOperation
) {
1382 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1388 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1389 if (result
.isSuccess()) {
1390 refreshShowDetails();
1391 refreshListOfFilesFragment();
1396 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1397 if (result
.isSuccess()) {
1398 refreshShowDetails();
1399 refreshListOfFilesFragment();
1401 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1402 cleanSecondFragment();
1403 refreshListOfFilesFragment();
1407 private void refreshShowDetails() {
1408 FileFragment details
= getSecondFragment();
1409 if (details
!= null
) {
1410 OCFile file
= details
.getFile();
1412 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1413 if (details
instanceof PreviewMediaFragment
) {
1414 // Refresh OCFile of the fragment
1415 ((PreviewMediaFragment
) details
).updateFile(file
);
1416 } else if (details
instanceof PreviewTextFragment
) {
1417 // Refresh OCFile of the fragment
1418 ((PreviewTextFragment
) details
).updateFile(file
);
1422 invalidateOptionsMenu();
1427 * Updates the view associated to the activity after the finish of an operation trying to remove a
1430 * @param operation Removal operation performed.
1431 * @param result Result of the removal.
1433 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1434 dismissLoadingDialog();
1436 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1440 if (result
.isSuccess()) {
1441 OCFile removedFile
= operation
.getFile();
1442 FileFragment second
= getSecondFragment();
1443 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1444 if (second
instanceof PreviewMediaFragment
) {
1445 ((PreviewMediaFragment
) second
).stopPreview(true
);
1447 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1448 cleanSecondFragment();
1450 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1451 refreshListOfFilesFragment();
1453 invalidateOptionsMenu();
1455 if (result
.isSslRecoverableException()) {
1456 mLastSslUntrustedServerResult
= result
;
1457 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1464 * Updates the view associated to the activity after the finish of an operation trying to move a
1467 * @param operation Move operation performed.
1468 * @param result Result of the move operation.
1470 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1471 if (result
.isSuccess()) {
1472 dismissLoadingDialog();
1473 refreshListOfFilesFragment();
1475 dismissLoadingDialog();
1477 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1478 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1482 } catch (NotFoundException e
) {
1483 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1490 * Updates the view associated to the activity after the finish of an operation trying to rename a
1493 * @param operation Renaming operation performed.
1494 * @param result Result of the renaming.
1496 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1497 dismissLoadingDialog();
1498 OCFile renamedFile
= operation
.getFile();
1499 if (result
.isSuccess()) {
1500 FileFragment details
= getSecondFragment();
1501 if (details
!= null
) {
1502 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile())) {
1503 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1504 showDetails(renamedFile
);
1506 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1507 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1508 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1509 int position
= ((PreviewMediaFragment
) details
).getPosition();
1510 startMediaPreview(renamedFile
, position
, true
);
1512 getFileOperationsHelper().openFile(renamedFile
);
1514 } else if (details
instanceof PreviewTextFragment
&& renamedFile
.equals(details
.getFile())) {
1515 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1516 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1517 startTextPreview(renamedFile
);
1519 getFileOperationsHelper().openFile(renamedFile
);
1524 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1525 refreshListOfFilesFragment();
1529 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1533 if (result
.isSslRecoverableException()) {
1534 mLastSslUntrustedServerResult
= result
;
1535 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1540 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1541 dismissLoadingDialog();
1542 OCFile syncedFile
= operation
.getLocalFile();
1543 if (!result
.isSuccess()) {
1544 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1545 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1546 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1547 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1553 if (operation
.transferWasRequested()) {
1554 onTransferStateChanged(syncedFile
, true
, true
);
1557 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1565 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1567 * @param operation Creation operation performed.
1568 * @param result Result of the creation.
1570 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1571 if (result
.isSuccess()) {
1572 dismissLoadingDialog();
1573 refreshListOfFilesFragment();
1575 dismissLoadingDialog();
1577 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1578 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1582 } catch (NotFoundException e
) {
1583 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1593 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1594 refreshListOfFilesFragment();
1595 FileFragment details
= getSecondFragment();
1596 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile())) {
1597 if (downloading
|| uploading
) {
1598 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1600 if (!file
.fileExists()) {
1601 cleanSecondFragment();
1603 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1611 private void requestForDownload() {
1612 Account account
= getAccount();
1613 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1614 Intent i
= new Intent(this, FileDownloader
.class);
1615 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1616 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1622 private OCFile
getCurrentDir() {
1623 OCFile file
= getFile();
1625 if (file
.isFolder()) {
1627 } else if (getStorageManager() != null
) {
1628 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1629 return getStorageManager().getFileByPath(parentPath
);
1635 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1636 long currentSyncTime
= System
.currentTimeMillis();
1638 mSyncInProgress
= true
;
1640 // perform folder synchronization
1641 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation(folder
,
1644 getFileOperationsHelper().isSharedSupported(),
1646 getStorageManager(),
1648 getApplicationContext()
1650 synchFolderOp
.execute(getAccount(), this, null
, null
);
1652 setSupportProgressBarIndeterminateVisibility(true
);
1654 setBackgroundText();
1658 * Show untrusted cert dialog
1660 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1661 // Show a dialog with the certificate info
1662 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
) result
.getException());
1663 FragmentManager fm
= getSupportFragmentManager();
1664 FragmentTransaction ft
= fm
.beginTransaction();
1665 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1668 private void requestForDownload(OCFile file
) {
1669 Account account
= getAccount();
1670 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1671 Intent i
= new Intent(this, FileDownloader
.class);
1672 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1673 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1678 private void sendDownloadedFile() {
1679 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1680 mWaitingToSend
= null
;
1685 * Requests the download of the received {@link OCFile} , updates the UI
1686 * to monitor the download progress and prepares the activity to send the file
1687 * when the download finishes.
1689 * @param file {@link OCFile} to download and preview.
1691 public void startDownloadForSending(OCFile file
) {
1692 mWaitingToSend
= file
;
1693 requestForDownload(mWaitingToSend
);
1694 boolean hasSecondFragment
= (getSecondFragment() != null
);
1695 updateFragmentsVisibility(hasSecondFragment
);
1699 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1701 * @param file Image {@link OCFile} to show.
1703 public void startImagePreview(OCFile file
) {
1704 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1705 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1706 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1707 startActivity(showDetailsIntent
);
1711 * Stars the preview of an already down media {@link OCFile}.
1713 * @param file Media {@link OCFile} to preview.
1714 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1715 * @param autoplay When 'true', the playback will start without user interactions.
1717 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1718 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1719 setSecondFragment(mediaFragment
);
1720 updateFragmentsVisibility(true
);
1721 updateNavigationElementsInActionBar(file
);
1726 * Stars the preview of a text file {@link OCFile}.
1728 * @param file Text {@link OCFile} to preview.
1730 public void startTextPreview(OCFile file
) {
1731 Bundle args
= new Bundle();
1732 args
.putParcelable(EXTRA_FILE
, file
);
1733 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1734 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(), PreviewTextFragment
.class.getName(), args
);
1735 setSecondFragment(textPreviewFragment
);
1736 updateFragmentsVisibility(true
);
1737 updateNavigationElementsInActionBar(file
);
1742 * Requests the download of the received {@link OCFile} , updates the UI
1743 * to monitor the download progress and prepares the activity to preview
1744 * or open the file when the download finishes.
1746 * @param file {@link OCFile} to download and preview.
1748 public void startDownloadForPreview(OCFile file
) {
1749 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1750 setSecondFragment(detailFragment
);
1751 mWaitingToPreview
= file
;
1752 requestForDownload();
1753 updateFragmentsVisibility(true
);
1754 updateNavigationElementsInActionBar(file
);
1759 public void cancelTransference(OCFile file
) {
1760 getFileOperationsHelper().cancelTransference(file
);
1761 if (mWaitingToPreview
!= null
&&
1762 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1763 mWaitingToPreview
= null
;
1765 if (mWaitingToSend
!= null
&&
1766 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1767 mWaitingToSend
= null
;
1769 onTransferStateChanged(file
, false
, false
);
1773 public void onRefresh(boolean ignoreETag
) {
1774 refreshList(ignoreETag
);
1778 public void onRefresh() {
1782 private void refreshList(boolean ignoreETag
) {
1783 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1784 if (listOfFiles
!= null
) {
1785 OCFile folder
= listOfFiles
.getCurrentFile();
1786 if (folder
!= null
) {
1787 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1788 listDirectory(mFile);*/
1789 startSyncFolderOperation(folder
, ignoreETag
);