1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.InvalidClassException
;
24 import android
.accounts
.Account
;
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.support.v4.content.LocalBroadcastManager;
49 import android
.util
.Log
;
50 import android
.view
.View
;
51 import android
.view
.ViewGroup
;
52 import android
.widget
.ArrayAdapter
;
53 import android
.widget
.TextView
;
54 import android
.widget
.Toast
;
56 import com
.actionbarsherlock
.app
.ActionBar
;
57 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
58 import com
.actionbarsherlock
.view
.Menu
;
59 import com
.actionbarsherlock
.view
.MenuInflater
;
60 import com
.actionbarsherlock
.view
.MenuItem
;
61 import com
.actionbarsherlock
.view
.Window
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.datamodel
.OCFile
;
65 import com
.owncloud
.android
.files
.services
.FileDownloader
;
66 import com
.owncloud
.android
.files
.services
.FileObserverService
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
70 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
72 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
76 import com
.owncloud
.android
.operations
.CreateShareOperation
;
77 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
78 import com
.owncloud
.android
.operations
.RenameFileOperation
;
79 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
80 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
81 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
82 import com
.owncloud
.android
.services
.OperationsService
;
83 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
84 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
86 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
87 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
88 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
89 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
90 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
92 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
93 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
94 import com
.owncloud
.android
.utils
.DisplayUtils
;
95 import com
.owncloud
.android
.utils
.Log_OC
;
99 * Displays, what files the user has available in his ownCloud.
101 * @author Bartek Przybylski
102 * @author David A. Velasco
105 public class FileDisplayActivity
extends HookActivity
implements
106 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
, EditNameDialogListener
{
108 private ArrayAdapter
<String
> mDirectories
;
110 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
111 private UploadFinishReceiver mUploadFinishReceiver
;
112 private DownloadFinishReceiver mDownloadFinishReceiver
;
113 //private OperationsServiceReceiver mOperationsServiceReceiver;
114 private FileDownloaderBinder mDownloaderBinder
= null
;
115 private FileUploaderBinder mUploaderBinder
= null
;
116 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
117 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
119 private boolean mDualPane
;
120 private View mLeftFragmentContainer
;
121 private View mRightFragmentContainer
;
123 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
124 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
125 //private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
126 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
128 public static final int DIALOG_SHORT_WAIT
= 0;
129 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
130 //private static final int DIALOG_SSL_VALIDATOR = 2;
131 private static final int DIALOG_CERT_NOT_SAVED
= 2;
133 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
135 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
136 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
138 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
140 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
143 private OCFile mWaitingToPreview
;
145 private boolean mSyncInProgress
= false
;
146 //private boolean mRefreshSharesInProgress = false;
148 private String DIALOG_UNTRUSTED_CERT
;
150 private OCFile mWaitingToSend
;
153 protected void onCreate(Bundle savedInstanceState
) {
154 Log_OC
.d(TAG
, "onCreate() start");
155 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
157 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
159 /// bindings to transference services
160 mUploadConnection
= new ListServiceConnection();
161 mDownloadConnection
= new ListServiceConnection();
162 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
163 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
165 // PIN CODE request ; best location is to decide, let's try this first
166 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
168 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
173 Intent observer_intent
= new Intent(this, FileObserverService
.class);
174 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
175 startService(observer_intent
);
177 /// Load of saved instance state
178 if(savedInstanceState
!= null
) {
179 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
180 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
181 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
182 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
185 mWaitingToPreview
= null
;
186 mSyncInProgress
= false
;
187 //mRefreshSharesInProgress = false;
188 mWaitingToSend
= null
;
193 // Inflate and set the layout view
194 setContentView(R
.layout
.files
);
195 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
196 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
197 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
198 if (savedInstanceState
== null
) {
199 createMinFragments();
201 Log_OC
.d(TAG
, "Init the secondFragment again");
203 initFragmentsWithFile();
208 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
209 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
210 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
212 Log_OC
.d(TAG
, "onCreate() end");
216 protected void onStart() {
218 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
219 refeshListOfFilesFragment();
223 protected void onDestroy() {
225 if (mDownloadConnection
!= null
)
226 unbindService(mDownloadConnection
);
227 if (mUploadConnection
!= null
)
228 unbindService(mUploadConnection
);
232 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
235 protected void onAccountSet(boolean stateWasRecovered
) {
236 super.onAccountSet(stateWasRecovered
);
237 if (getAccount() != null
) {
238 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
239 OCFile file
= getFile();
240 // get parent from path
241 String parentPath
= "";
243 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
244 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
245 // get parent from path
246 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
247 if (getStorageManager().getFileByPath(parentPath
) == null
)
248 file
= null
; // not able to know the directory where the file is uploading
250 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
254 // fall back to root folder
255 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
258 setNavigationListWithFolder(file
);
260 if (!stateWasRecovered
) {
261 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
262 initFragmentsWithFile();
263 if (file
.isFolder()) {
264 startSyncFolderOperation(file
);
268 updateFragmentsVisibility(!file
.isFolder());
269 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
275 private void setNavigationListWithFolder(OCFile file
) {
276 mDirectories
.clear();
277 OCFile fileIt
= file
;
279 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
280 if (fileIt
.isFolder()) {
281 mDirectories
.add(fileIt
.getFileName());
283 // get parent from path
284 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
285 fileIt
= getStorageManager().getFileByPath(parentPath
);
287 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
291 private void createMinFragments() {
292 OCFileListFragment listOfFiles
= new OCFileListFragment();
293 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
294 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
295 transaction
.commit();
298 private void initFragmentsWithFile() {
299 if (getAccount() != null
&& getFile() != null
) {
301 OCFileListFragment listOfFiles
= getListOfFilesFragment();
302 if (listOfFiles
!= null
) {
303 listOfFiles
.listDirectory(getCurrentDir());
305 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
309 OCFile file
= getFile();
310 Fragment secondFragment
= chooseInitialSecondFragment(file
);
311 if (secondFragment
!= null
) {
312 setSecondFragment(secondFragment
);
313 updateFragmentsVisibility(true
);
314 updateNavigationElementsInActionBar(file
);
317 cleanSecondFragment();
321 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
322 if (getAccount() == null
) {
323 Log
.wtf(TAG
, "\t account is NULL");
325 if (getFile() == null
) {
326 Log
.wtf(TAG
, "\t file is NULL");
331 private Fragment
chooseInitialSecondFragment(OCFile file
) {
332 Fragment secondFragment
= null
;
333 if (file
!= null
&& !file
.isFolder()) {
334 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
335 && file
.getLastSyncDateForProperties() > 0 // temporal fix
337 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
338 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
339 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
342 secondFragment
= new FileDetailFragment(file
, getAccount());
345 return secondFragment
;
350 * Replaces the second fragment managed by the activity with the received as
353 * Assumes never will be more than two fragments managed at the same time.
355 * @param fragment New second Fragment to set.
357 private void setSecondFragment(Fragment fragment
) {
358 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
359 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
360 transaction
.commit();
364 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
366 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
369 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
373 } else if (existsSecondFragment
) {
374 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
375 mLeftFragmentContainer
.setVisibility(View
.GONE
);
377 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
378 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
382 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
383 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
385 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
386 mRightFragmentContainer
.setVisibility(View
.GONE
);
392 private OCFileListFragment
getListOfFilesFragment() {
393 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
394 if (listOfFiles
!= null
) {
395 return (OCFileListFragment
)listOfFiles
;
397 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
401 protected FileFragment
getSecondFragment() {
402 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
403 if (second
!= null
) {
404 return (FileFragment
)second
;
409 public void cleanSecondFragment() {
410 Fragment second
= getSecondFragment();
411 if (second
!= null
) {
412 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
416 updateFragmentsVisibility(false
);
417 updateNavigationElementsInActionBar(null
);
420 protected void refeshListOfFilesFragment() {
421 OCFileListFragment fileListFragment
= getListOfFilesFragment();
422 if (fileListFragment
!= null
) {
423 fileListFragment
.listDirectory();
427 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
428 FileFragment secondFragment
= getSecondFragment();
429 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
430 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
431 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
432 OCFile fileInFragment
= detailsFragment
.getFile();
433 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
434 // the user browsed to other file ; forget the automatic preview
435 mWaitingToPreview
= null
;
437 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
438 // grant that the right panel updates the progress bar
439 detailsFragment
.listenForTransferProgress();
440 detailsFragment
.updateFileDetails(true
, false
);
442 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
443 // update the right panel
444 boolean detailsFragmentChanged
= false
;
447 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
448 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
449 startMediaPreview(mWaitingToPreview
, 0, true
);
450 detailsFragmentChanged
= true
;
452 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
455 mWaitingToPreview
= null
;
457 if (!detailsFragmentChanged
) {
458 detailsFragment
.updateFileDetails(false
, (success
));
465 public boolean onCreateOptionsMenu(Menu menu
) {
466 MenuInflater inflater
= getSherlock().getMenuInflater();
467 inflater
.inflate(R
.menu
.main_menu
, menu
);
472 public boolean onOptionsItemSelected(MenuItem item
) {
473 boolean retval
= true
;
474 switch (item
.getItemId()) {
475 case R
.id
.action_create_dir
: {
476 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
477 dialog
.show(getSupportFragmentManager(), "createdirdialog");
480 case R
.id
.action_sync_account
: {
481 startSynchronization();
484 case R
.id
.action_upload
: {
485 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
488 case R
.id
.action_settings
: {
489 Intent settingsIntent
= new Intent(this, Preferences
.class);
490 startActivity(settingsIntent
);
493 case android
.R
.id
.home
: {
494 FileFragment second
= getSecondFragment();
495 OCFile currentDir
= getCurrentDir();
496 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
497 (second
!= null
&& second
.getFile() != null
)) {
504 retval
= super.onOptionsItemSelected(item
);
509 private void startSynchronization() {
510 Log_OC
.e(TAG
, "Got to start sync");
511 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
512 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
513 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
514 Bundle bundle
= new Bundle();
515 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
516 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
517 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
518 ContentResolver
.requestSync(
520 MainApp
.getAuthority(), bundle
);
522 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
523 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
524 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
525 builder
.setExpedited(true
);
526 builder
.setManual(true
);
528 SyncRequest request
= builder
.build();
529 ContentResolver
.requestSync(request
);
535 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
536 if (itemPosition
!= 0) {
537 String targetPath
= "";
538 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
539 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
541 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
542 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
543 if (targetFolder
!= null
) {
544 browseTo(targetFolder
);
547 // the next operation triggers a new call to this method, but it's necessary to
548 // ensure that the name exposed in the action bar is the current directory when the
549 // user selected it in the navigation list
550 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
551 getSupportActionBar().setSelectedNavigationItem(0);
557 * Called, when the user selected something for uploading
559 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
560 super.onActivityResult(requestCode
, resultCode
, data
);
562 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
563 requestSimpleUpload(data
, resultCode
);
565 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
566 requestMultipleUpload(data
, resultCode
);
571 private void requestMultipleUpload(Intent data
, int resultCode
) {
572 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
573 if (filePaths
!= null
) {
574 String
[] remotePaths
= new String
[filePaths
.length
];
575 String remotePathBase
= "";
576 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
577 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
579 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
580 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
581 for (int j
= 0; j
< remotePaths
.length
; j
++) {
582 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
585 Intent i
= new Intent(this, FileUploader
.class);
586 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
587 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
588 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
589 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
590 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
591 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
595 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
596 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
603 private void requestSimpleUpload(Intent data
, int resultCode
) {
604 String filepath
= null
;
606 Uri selectedImageUri
= data
.getData();
608 String filemanagerstring
= selectedImageUri
.getPath();
609 String selectedImagePath
= getPath(selectedImageUri
);
611 if (selectedImagePath
!= null
)
612 filepath
= selectedImagePath
;
614 filepath
= filemanagerstring
;
616 } catch (Exception e
) {
617 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
621 if (filepath
== null
) {
622 Log_OC
.e(TAG
, "Couldnt resolve path to file");
623 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
629 Intent i
= new Intent(this, FileUploader
.class);
630 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
632 String remotepath
= new String();
633 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
634 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
636 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
637 remotepath
+= OCFile
.PATH_SEPARATOR
;
638 remotepath
+= new File(filepath
).getName();
640 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
641 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
642 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
643 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
644 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
649 public void onBackPressed() {
650 OCFileListFragment listOfFiles
= getListOfFilesFragment();
651 if (mDualPane
|| getSecondFragment() == null
) {
652 if (listOfFiles
!= null
) { // should never be null, indeed
653 if (mDirectories
.getCount() <= 1) {
657 int levelsUp
= listOfFiles
.onBrowseUp();
658 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
663 if (listOfFiles
!= null
) { // should never be null, indeed
664 setFile(listOfFiles
.getCurrentFile());
666 cleanSecondFragment();
671 protected void onSaveInstanceState(Bundle outState
) {
672 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
673 Log_OC
.e(TAG
, "onSaveInstanceState() start");
674 super.onSaveInstanceState(outState
);
675 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
676 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
677 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
678 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
680 Log_OC
.d(TAG
, "onSaveInstanceState() end");
686 protected void onResume() {
688 Log_OC
.e(TAG
, "onResume() start");
690 // Listen for sync messages
691 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
692 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
693 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
694 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
695 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
696 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
697 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
698 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
699 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
701 // Listen for upload messages
702 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
703 mUploadFinishReceiver
= new UploadFinishReceiver();
704 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
706 // Listen for download messages
707 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
708 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
709 mDownloadFinishReceiver
= new DownloadFinishReceiver();
710 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
712 // Listen for messages from the OperationsService
714 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
715 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
716 mOperationsServiceReceiver = new OperationsServiceReceiver();
717 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
720 Log_OC
.d(TAG
, "onResume() end");
725 protected void onPause() {
727 Log_OC
.e(TAG
, "onPause() start");
728 if (mSyncBroadcastReceiver
!= null
) {
729 unregisterReceiver(mSyncBroadcastReceiver
);
730 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
731 mSyncBroadcastReceiver
= null
;
733 if (mUploadFinishReceiver
!= null
) {
734 unregisterReceiver(mUploadFinishReceiver
);
735 mUploadFinishReceiver
= null
;
737 if (mDownloadFinishReceiver
!= null
) {
738 unregisterReceiver(mDownloadFinishReceiver
);
739 mDownloadFinishReceiver
= null
;
742 if (mOperationsServiceReceiver != null) {
743 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
744 mOperationsServiceReceiver = null;
747 Log_OC
.d(TAG
, "onPause() end");
752 protected Dialog
onCreateDialog(int id
) {
753 Dialog dialog
= null
;
754 AlertDialog
.Builder builder
;
756 case DIALOG_SHORT_WAIT
: {
757 ProgressDialog working_dialog
= new ProgressDialog(this);
758 working_dialog
.setMessage(getResources().getString(
759 R
.string
.wait_a_moment
));
760 working_dialog
.setIndeterminate(true
);
761 working_dialog
.setCancelable(false
);
762 dialog
= working_dialog
;
765 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
767 String
[] items
= null
;
769 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
770 getString(R
.string
.actionbar_upload_from_apps
),
771 getString(R
.string
.actionbar_failed_instant_upload
) };
773 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
774 getString(R
.string
.actionbar_upload_from_apps
) };
776 if (InstantUploadActivity
.IS_ENABLED
)
781 builder
= new AlertDialog
.Builder(this);
782 builder
.setTitle(R
.string
.actionbar_upload
);
783 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
784 public void onClick(DialogInterface dialog
, int item
) {
787 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
788 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
789 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
791 // TODO create and handle new fragment
792 // LocalFileListFragment
794 } else if (item
== 1) {
795 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
796 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
797 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
798 ACTION_SELECT_CONTENT_FROM_APPS
);
799 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
800 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
801 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
802 startActivity(action
);
806 dialog
= builder
.create();
809 case DIALOG_CERT_NOT_SAVED
: {
810 builder
= new AlertDialog
.Builder(this);
811 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
812 builder
.setCancelable(false
);
813 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
815 public void onClick(DialogInterface dialog
, int which
) {
819 dialog
= builder
.create();
831 * Translates a content URI of an image to a physical path
833 * @param uri The URI to resolve
834 * @return The path to the image or null if it could not be found
836 public String
getPath(Uri uri
) {
837 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
838 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
839 if (cursor
!= null
) {
840 int column_index
= cursor
841 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
842 cursor
.moveToFirst();
843 return cursor
.getString(column_index
);
849 * Pushes a directory to the drop down list
850 * @param directory to push
851 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
853 public void pushDirname(OCFile directory
) {
854 if(!directory
.isFolder()){
855 throw new IllegalArgumentException("Only directories may be pushed!");
857 mDirectories
.insert(directory
.getFileName(), 0);
862 * Pops a directory name from the drop down list
863 * @return True, unless the stack is empty
865 public boolean popDirname() {
866 mDirectories
.remove(mDirectories
.getItem(0));
867 return !mDirectories
.isEmpty();
870 // Custom array adapter to override text colors
871 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
873 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
877 public View
getView(int position
, View convertView
, ViewGroup parent
) {
878 View v
= super.getView(position
, convertView
, parent
);
880 ((TextView
) v
).setTextColor(getResources().getColorStateList(
881 android
.R
.color
.white
));
883 fixRoot((TextView
) v
);
887 public View
getDropDownView(int position
, View convertView
,
889 View v
= super.getDropDownView(position
, convertView
, parent
);
891 ((TextView
) v
).setTextColor(getResources().getColorStateList(
892 android
.R
.color
.white
));
894 fixRoot((TextView
) v
);
898 private void fixRoot(TextView v
) {
899 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
900 v
.setText(R
.string
.default_display_name_for_root_folder
);
906 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
909 * {@link BroadcastReceiver} to enable syncing feedback in UI
912 public void onReceive(Context context
, Intent intent
) {
914 String event
= intent
.getAction();
915 Log_OC
.d(TAG
, "Received broadcast " + event
);
916 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
917 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
918 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
919 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
923 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
924 mSyncInProgress
= true
;
927 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
928 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
930 if (currentDir
== null
) {
931 // current folder was removed from the server
932 Toast
.makeText( FileDisplayActivity
.this,
933 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
939 if (currentFile
== null
&& !getFile().isFolder()) {
940 // currently selected file was removed in the server, and now we know it
941 cleanSecondFragment();
942 currentFile
= currentDir
;
945 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
946 OCFileListFragment fileListFragment
= getListOfFilesFragment();
947 if (fileListFragment
!= null
) {
948 fileListFragment
.listDirectory(currentDir
);
951 setFile(currentFile
);
954 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
957 if (synchResult != null &&
958 synchResult.isSuccess() &&
959 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
960 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
962 !mRefreshSharesInProgress &&
963 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
970 removeStickyBroadcast(intent
);
971 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
972 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
975 if (synchResult
!= null
) {
976 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
977 mLastSslUntrustedServerResult
= synchResult
;
980 } catch (RuntimeException e
) {
981 // avoid app crashes after changing the serial id of RemoteOperationResult
982 // in owncloud library with broadcast notifications pending to process
983 removeStickyBroadcast(intent
);
989 private class UploadFinishReceiver
extends BroadcastReceiver
{
991 * Once the file upload has finished -> update view
992 * @author David A. Velasco
993 * {@link BroadcastReceiver} to enable upload feedback in UI
996 public void onReceive(Context context
, Intent intent
) {
997 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
998 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
999 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1000 OCFile currentDir
= getCurrentDir();
1001 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1002 if (sameAccount
&& isDescendant
) {
1003 refeshListOfFilesFragment();
1011 * Class waiting for broadcast events from the {@link FielDownloader} service.
1013 * Updates the UI when a download is started or finished, provided that it is relevant for the
1016 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1018 public void onReceive(Context context
, Intent intent
) {
1019 boolean sameAccount
= isSameAccount(context
, intent
);
1020 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1021 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1023 if (sameAccount
&& isDescendant
) {
1024 refeshListOfFilesFragment();
1025 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1028 if (mWaitingToSend
!= null
) {
1029 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1030 if (mWaitingToSend
.isDown()) {
1031 sendDownloadedFile();
1035 removeStickyBroadcast(intent
);
1038 private boolean isDescendant(String downloadedRemotePath
) {
1039 OCFile currentDir
= getCurrentDir();
1040 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1043 private boolean isSameAccount(Context context
, Intent intent
) {
1044 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1045 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1051 * Class waiting for broadcast events from the {@link OperationsService}.
1053 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1054 * operation performed in {@link OperationsService}.
1056 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1057 * probably all the operations associated to the app model.
1059 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1062 public void onReceive(Context context
, Intent intent
) {
1063 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1065 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1066 //mRefreshSharesInProgress = false;
1068 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1069 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1070 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1071 && getStorageManager() != null
1073 refeshListOfFilesFragment();
1075 if ((getSharesResult
!= null
) &&
1076 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1077 mLastSslUntrustedServerResult
= getSharesResult
;
1078 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1081 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1088 public void browseToRoot() {
1089 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1090 if (listOfFiles
!= null
) { // should never be null, indeed
1091 while (mDirectories
.getCount() > 1) {
1094 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1095 listOfFiles
.listDirectory(root
);
1096 setFile(listOfFiles
.getCurrentFile());
1097 startSyncFolderOperation(root
);
1099 cleanSecondFragment();
1103 public void browseTo(OCFile folder
) {
1104 if (folder
== null
|| !folder
.isFolder()) {
1105 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1107 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1108 if (listOfFiles
!= null
) {
1109 setNavigationListWithFolder(folder
);
1110 listOfFiles
.listDirectory(folder
);
1111 setFile(listOfFiles
.getCurrentFile());
1112 startSyncFolderOperation(folder
);
1114 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1116 cleanSecondFragment();
1123 * Updates action bar and second fragment, if in dual pane mode.
1126 public void onBrowsedDownTo(OCFile directory
) {
1127 pushDirname(directory
);
1128 cleanSecondFragment();
1131 startSyncFolderOperation(directory
);
1136 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1138 * @param file Image {@link OCFile} to show.
1141 public void startImagePreview(OCFile file
) {
1142 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1143 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1144 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1145 startActivity(showDetailsIntent
);
1149 * Stars the preview of an already down media {@link OCFile}.
1151 * @param file Media {@link OCFile} to preview.
1152 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1153 * @param autoplay When 'true', the playback will start without user interactions.
1156 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1157 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1158 setSecondFragment(mediaFragment
);
1159 updateFragmentsVisibility(true
);
1160 updateNavigationElementsInActionBar(file
);
1165 * Requests the download of the received {@link OCFile} , updates the UI
1166 * to monitor the download progress and prepares the activity to preview
1167 * or open the file when the download finishes.
1169 * @param file {@link OCFile} to download and preview.
1172 public void startDownloadForPreview(OCFile file
) {
1173 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1174 setSecondFragment(detailFragment
);
1175 mWaitingToPreview
= file
;
1176 requestForDownload();
1177 updateFragmentsVisibility(true
);
1178 updateNavigationElementsInActionBar(file
);
1184 * Shows the information of the {@link OCFile} received as a
1185 * parameter in the second fragment.
1187 * @param file {@link OCFile} whose details will be shown
1190 public void showDetails(OCFile file
) {
1191 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1192 setSecondFragment(detailFragment
);
1193 updateFragmentsVisibility(true
);
1194 updateNavigationElementsInActionBar(file
);
1202 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1203 ActionBar actionBar
= getSupportActionBar();
1204 if (chosenFile
== null
|| mDualPane
) {
1205 // only list of files - set for browsing through folders
1206 OCFile currentDir
= getCurrentDir();
1207 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1208 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1209 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1211 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1213 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1214 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1217 actionBar
.setDisplayHomeAsUpEnabled(true
);
1218 actionBar
.setDisplayShowTitleEnabled(true
);
1219 actionBar
.setTitle(chosenFile
.getFileName());
1220 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1229 public void onFileStateChanged() {
1230 refeshListOfFilesFragment();
1231 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1239 public FileDownloaderBinder
getFileDownloaderBinder() {
1240 return mDownloaderBinder
;
1248 public FileUploaderBinder
getFileUploaderBinder() {
1249 return mUploaderBinder
;
1253 /** Defines callbacks for service binding, passed to bindService() */
1254 private class ListServiceConnection
implements ServiceConnection
{
1257 public void onServiceConnected(ComponentName component
, IBinder service
) {
1258 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1259 Log_OC
.d(TAG
, "Download service connected");
1260 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1261 if (mWaitingToPreview
!= null
) {
1262 requestForDownload();
1265 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1266 Log_OC
.d(TAG
, "Upload service connected");
1267 mUploaderBinder
= (FileUploaderBinder
) service
;
1271 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1272 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1273 if (listOfFiles
!= null
) {
1274 listOfFiles
.listDirectory();
1276 FileFragment secondFragment
= getSecondFragment();
1277 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1278 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1279 detailFragment
.listenForTransferProgress();
1280 detailFragment
.updateFileDetails(false
, false
);
1285 public void onServiceDisconnected(ComponentName component
) {
1286 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1287 Log_OC
.d(TAG
, "Download service disconnected");
1288 mDownloaderBinder
= null
;
1289 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1290 Log_OC
.d(TAG
, "Upload service disconnected");
1291 mUploaderBinder
= null
;
1299 * Launch an intent to request the PIN code to the user before letting him use the app
1301 private void requestPinCode() {
1302 boolean pinStart
= false
;
1303 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1304 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1306 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1307 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1314 public void onSavedCertificate() {
1315 startSyncFolderOperation(getCurrentDir());
1320 public void onFailedSavingCertificate() {
1321 showDialog(DIALOG_CERT_NOT_SAVED
);
1325 public void onCancelCertificate() {
1330 * Updates the view associated to the activity after the finish of some operation over files
1331 * in the current account.
1333 * @param operation Removal operation performed.
1334 * @param result Result of the removal.
1337 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1338 super.onRemoteOperationFinish(operation
, result
);
1340 if (operation
instanceof RemoveFileOperation
) {
1341 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1343 } else if (operation
instanceof RenameFileOperation
) {
1344 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1346 } else if (operation
instanceof SynchronizeFileOperation
) {
1347 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1349 } else if (operation
instanceof CreateFolderOperation
) {
1350 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1352 } else if (operation
instanceof CreateShareOperation
) {
1353 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1355 } else if (operation
instanceof UnshareLinkOperation
) {
1356 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1363 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1364 if (result
.isSuccess()) {
1365 refreshShowDetails();
1366 refeshListOfFilesFragment();
1371 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1372 if (result
.isSuccess()) {
1373 refreshShowDetails();
1374 refeshListOfFilesFragment();
1375 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1376 cleanSecondFragment();
1377 refeshListOfFilesFragment();
1381 private void refreshShowDetails() {
1382 FileFragment details
= getSecondFragment();
1383 if (details
!= null
) {
1384 OCFile file
= details
.getFile();
1386 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1387 if (details
instanceof PreviewMediaFragment
) {
1388 // Refresh OCFile of the fragment
1389 ((PreviewMediaFragment
) details
).updateFile(file
);
1394 invalidateOptionsMenu();
1399 * Updates the view associated to the activity after the finish of an operation trying to remove a
1402 * @param operation Removal operation performed.
1403 * @param result Result of the removal.
1405 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1406 dismissLoadingDialog();
1407 if (result
.isSuccess()) {
1408 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1410 OCFile removedFile
= operation
.getFile();
1411 getSecondFragment();
1412 FileFragment second
= getSecondFragment();
1413 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1414 cleanSecondFragment();
1416 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1417 refeshListOfFilesFragment();
1421 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1423 if (result
.isSslRecoverableException()) {
1424 mLastSslUntrustedServerResult
= result
;
1425 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1431 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1433 * @param operation Creation operation performed.
1434 * @param result Result of the creation.
1436 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1437 if (result
.isSuccess()) {
1438 dismissLoadingDialog();
1439 refeshListOfFilesFragment();
1442 dismissLoadingDialog();
1443 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1444 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1447 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1450 } catch (NotFoundException e
) {
1451 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1459 * Updates the view associated to the activity after the finish of an operation trying to rename a
1462 * @param operation Renaming operation performed.
1463 * @param result Result of the renaming.
1465 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1466 dismissLoadingDialog();
1467 OCFile renamedFile
= operation
.getFile();
1468 if (result
.isSuccess()) {
1470 FileFragment details
= getSecondFragment();
1471 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1472 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1475 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1476 refeshListOfFilesFragment();
1480 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1481 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1483 // TODO throw again the new rename dialog
1484 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1485 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1488 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1490 if (result
.isSslRecoverableException()) {
1491 mLastSslUntrustedServerResult
= result
;
1492 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1499 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1500 dismissLoadingDialog();
1501 OCFile syncedFile
= operation
.getLocalFile();
1502 if (!result
.isSuccess()) {
1503 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1504 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1505 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1506 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1512 if (operation
.transferWasRequested()) {
1513 refeshListOfFilesFragment();
1514 onTransferStateChanged(syncedFile
, true
, true
);
1517 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1528 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1530 FileFragment details
= getSecondFragment();
1531 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1532 if (downloading
|| uploading
) {
1533 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1535 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1542 public void onDismiss(EditNameDialog dialog
) {
1543 if (dialog
.getResult()) {
1544 String newDirectoryName
= dialog
.getNewFilename().trim();
1545 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1546 if (newDirectoryName
.length() > 0) {
1547 String path
= getCurrentDir().getRemotePath();
1550 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1551 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1552 operation
.execute( getAccount(),
1553 FileDisplayActivity
.this,
1554 FileDisplayActivity
.this,
1556 FileDisplayActivity
.this);
1558 showLoadingDialog();
1564 private void requestForDownload() {
1565 Account account
= getAccount();
1566 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1567 Intent i
= new Intent(this, FileDownloader
.class);
1568 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1569 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1575 private OCFile
getCurrentDir() {
1576 OCFile file
= getFile();
1578 if (file
.isFolder()) {
1580 } else if (getStorageManager() != null
) {
1581 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1582 return getStorageManager().getFileByPath(parentPath
);
1588 public void startSyncFolderOperation(OCFile folder
) {
1589 long currentSyncTime
= System
.currentTimeMillis();
1591 mSyncInProgress
= true
;
1593 // perform folder synchronization
1594 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1597 getFileOperationsHelper().isSharedSupported(this),
1598 getStorageManager(),
1600 getApplicationContext()
1602 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1604 setSupportProgressBarIndeterminateVisibility(true
);
1608 private void startGetShares() {
1609 // Get shared files/folders
1610 Intent intent = new Intent(this, OperationsService.class);
1611 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1612 startService(intent);
1614 mRefreshSharesInProgress = true;
1619 * Show untrusted cert dialog
1621 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1622 // Show a dialog with the certificate info
1623 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1624 FragmentManager fm
= getSupportFragmentManager();
1625 FragmentTransaction ft
= fm
.beginTransaction();
1626 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1630 * Requests the download of the received {@link OCFile} , updates the UI
1631 * to monitor the download progress and prepares the activity to send the file
1632 * when the download finishes.
1634 * @param file {@link OCFile} to download and preview.
1637 public void startDownloadForSending(OCFile file
) {
1638 mWaitingToSend
= file
;
1639 requestForDownload(mWaitingToSend
);
1640 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1641 updateFragmentsVisibility(hasSecondFragment
);
1644 private void requestForDownload(OCFile file
) {
1645 Account account
= getAccount();
1646 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1647 Intent i
= new Intent(this, FileDownloader
.class);
1648 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1649 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1654 private void sendDownloadedFile(){
1655 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1656 mWaitingToSend
= null
;