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
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.Dialog
;
26 import android
.app
.ProgressDialog
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.ComponentName
;
29 import android
.content
.ContentResolver
;
30 import android
.content
.Context
;
31 import android
.content
.DialogInterface
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.content
.SyncRequest
;
37 import android
.content
.res
.Resources
.NotFoundException
;
38 import android
.database
.Cursor
;
39 import android
.net
.Uri
;
40 import android
.os
.Bundle
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.provider
.MediaStore
;
44 import android
.support
.v4
.app
.Fragment
;
45 import android
.support
.v4
.app
.FragmentManager
;
46 import android
.support
.v4
.app
.FragmentTransaction
;
47 //import android.support.v4.content.LocalBroadcastManager;
48 import android
.util
.Log
;
49 import android
.view
.View
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ArrayAdapter
;
52 import android
.widget
.TextView
;
53 import android
.widget
.Toast
;
55 import com
.actionbarsherlock
.app
.ActionBar
;
56 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
57 import com
.actionbarsherlock
.view
.Menu
;
58 import com
.actionbarsherlock
.view
.MenuInflater
;
59 import com
.actionbarsherlock
.view
.MenuItem
;
60 import com
.actionbarsherlock
.view
.Window
;
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
.FileObserverService
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
71 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
75 import com
.owncloud
.android
.operations
.CreateShareOperation
;
76 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
77 import com
.owncloud
.android
.operations
.RenameFileOperation
;
78 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
79 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
80 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
81 import com
.owncloud
.android
.services
.OperationsService
;
82 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
83 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
86 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
87 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
88 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
89 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
92 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
93 import com
.owncloud
.android
.utils
.DisplayUtils
;
94 import com
.owncloud
.android
.utils
.Log_OC
;
98 * Displays, what files the user has available in his ownCloud.
100 * @author Bartek Przybylski
101 * @author David A. Velasco
104 public class FileDisplayActivity
extends HookActivity
implements
105 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
, EditNameDialogListener
{
107 private ArrayAdapter
<String
> mDirectories
;
109 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
110 private UploadFinishReceiver mUploadFinishReceiver
;
111 private DownloadFinishReceiver mDownloadFinishReceiver
;
112 //private OperationsServiceReceiver mOperationsServiceReceiver;
113 private FileDownloaderBinder mDownloaderBinder
= null
;
114 private FileUploaderBinder mUploaderBinder
= null
;
115 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
116 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
118 private boolean mDualPane
;
119 private View mLeftFragmentContainer
;
120 private View mRightFragmentContainer
;
122 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
123 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
124 //private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
125 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
127 public static final int DIALOG_SHORT_WAIT
= 0;
128 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
129 //private static final int DIALOG_SSL_VALIDATOR = 2;
130 private static final int DIALOG_CERT_NOT_SAVED
= 2;
132 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
134 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
135 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
137 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
139 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
140 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
142 private OCFile mWaitingToPreview
;
144 private boolean mSyncInProgress
= false
;
145 //private boolean mRefreshSharesInProgress = false;
147 private String DIALOG_UNTRUSTED_CERT
;
149 private OCFile mWaitingToSend
;
152 protected void onCreate(Bundle savedInstanceState
) {
153 Log_OC
.d(TAG
, "onCreate() start");
154 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
156 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
158 /// bindings to transference services
159 mUploadConnection
= new ListServiceConnection();
160 mDownloadConnection
= new ListServiceConnection();
161 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
162 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
164 // PIN CODE request ; best location is to decide, let's try this first
165 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
167 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
172 Intent observer_intent
= new Intent(this, FileObserverService
.class);
173 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
174 startService(observer_intent
);
176 /// Load of saved instance state
177 if(savedInstanceState
!= null
) {
178 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
179 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
180 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
181 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
184 mWaitingToPreview
= null
;
185 mSyncInProgress
= false
;
186 //mRefreshSharesInProgress = false;
187 mWaitingToSend
= null
;
192 // Inflate and set the layout view
193 setContentView(R
.layout
.files
);
194 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
195 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
196 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
197 if (savedInstanceState
== null
) {
198 createMinFragments();
200 Log_OC
.d(TAG
, "Init the secondFragment again");
202 initFragmentsWithFile();
207 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
208 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
209 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
211 Log_OC
.d(TAG
, "onCreate() end");
215 protected void onStart() {
217 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
218 refeshListOfFilesFragment();
222 protected void onDestroy() {
224 if (mDownloadConnection
!= null
)
225 unbindService(mDownloadConnection
);
226 if (mUploadConnection
!= null
)
227 unbindService(mUploadConnection
);
231 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
234 protected void onAccountSet(boolean stateWasRecovered
) {
235 super.onAccountSet(stateWasRecovered
);
236 if (getAccount() != null
) {
237 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
238 OCFile file
= getFile();
239 // get parent from path
240 String parentPath
= "";
242 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
243 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
244 // get parent from path
245 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
246 if (getStorageManager().getFileByPath(parentPath
) == null
)
247 file
= null
; // not able to know the directory where the file is uploading
249 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
253 // fall back to root folder
254 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
257 setNavigationListWithFolder(file
);
259 if (!stateWasRecovered
) {
260 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
261 initFragmentsWithFile();
262 if (file
.isFolder()) {
263 startSyncFolderOperation(file
);
267 updateFragmentsVisibility(!file
.isFolder());
268 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
274 private void setNavigationListWithFolder(OCFile file
) {
275 mDirectories
.clear();
276 OCFile fileIt
= file
;
278 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
279 if (fileIt
.isFolder()) {
280 mDirectories
.add(fileIt
.getFileName());
282 // get parent from path
283 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
284 fileIt
= getStorageManager().getFileByPath(parentPath
);
286 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
290 private void createMinFragments() {
291 OCFileListFragment listOfFiles
= new OCFileListFragment();
292 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
293 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
294 transaction
.commit();
297 private void initFragmentsWithFile() {
298 if (getAccount() != null
&& getFile() != null
) {
300 OCFileListFragment listOfFiles
= getListOfFilesFragment();
301 if (listOfFiles
!= null
) {
302 listOfFiles
.listDirectory(getCurrentDir());
304 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
308 OCFile file
= getFile();
309 Fragment secondFragment
= chooseInitialSecondFragment(file
);
310 if (secondFragment
!= null
) {
311 setSecondFragment(secondFragment
);
312 updateFragmentsVisibility(true
);
313 updateNavigationElementsInActionBar(file
);
316 cleanSecondFragment();
320 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
321 if (getAccount() == null
) {
322 Log
.wtf(TAG
, "\t account is NULL");
324 if (getFile() == null
) {
325 Log
.wtf(TAG
, "\t file is NULL");
330 private Fragment
chooseInitialSecondFragment(OCFile file
) {
331 Fragment secondFragment
= null
;
332 if (file
!= null
&& !file
.isFolder()) {
333 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
334 && file
.getLastSyncDateForProperties() > 0 // temporal fix
336 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
337 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
338 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
341 secondFragment
= new FileDetailFragment(file
, getAccount());
344 return secondFragment
;
349 * Replaces the second fragment managed by the activity with the received as
352 * Assumes never will be more than two fragments managed at the same time.
354 * @param fragment New second Fragment to set.
356 private void setSecondFragment(Fragment fragment
) {
357 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
358 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
359 transaction
.commit();
363 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
365 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
368 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
372 } else if (existsSecondFragment
) {
373 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
374 mLeftFragmentContainer
.setVisibility(View
.GONE
);
376 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
377 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
381 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
382 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
384 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
385 mRightFragmentContainer
.setVisibility(View
.GONE
);
391 private OCFileListFragment
getListOfFilesFragment() {
392 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
393 if (listOfFiles
!= null
) {
394 return (OCFileListFragment
)listOfFiles
;
396 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
400 protected FileFragment
getSecondFragment() {
401 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
402 if (second
!= null
) {
403 return (FileFragment
)second
;
408 public void cleanSecondFragment() {
409 Fragment second
= getSecondFragment();
410 if (second
!= null
) {
411 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
415 updateFragmentsVisibility(false
);
416 updateNavigationElementsInActionBar(null
);
419 protected void refeshListOfFilesFragment() {
420 OCFileListFragment fileListFragment
= getListOfFilesFragment();
421 if (fileListFragment
!= null
) {
422 fileListFragment
.listDirectory();
426 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
427 FileFragment secondFragment
= getSecondFragment();
428 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
429 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
430 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
431 OCFile fileInFragment
= detailsFragment
.getFile();
432 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
433 // the user browsed to other file ; forget the automatic preview
434 mWaitingToPreview
= null
;
436 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
437 // grant that the right panel updates the progress bar
438 detailsFragment
.listenForTransferProgress();
439 detailsFragment
.updateFileDetails(true
, false
);
441 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
442 // update the right panel
443 boolean detailsFragmentChanged
= false
;
446 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
447 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
448 startMediaPreview(mWaitingToPreview
, 0, true
);
449 detailsFragmentChanged
= true
;
451 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
454 mWaitingToPreview
= null
;
456 if (!detailsFragmentChanged
) {
457 detailsFragment
.updateFileDetails(false
, (success
));
464 public boolean onCreateOptionsMenu(Menu menu
) {
465 MenuInflater inflater
= getSherlock().getMenuInflater();
466 inflater
.inflate(R
.menu
.main_menu
, menu
);
471 public boolean onOptionsItemSelected(MenuItem item
) {
472 boolean retval
= true
;
473 switch (item
.getItemId()) {
474 case R
.id
.action_create_dir
: {
475 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
476 dialog
.show(getSupportFragmentManager(), "createdirdialog");
479 case R
.id
.action_sync_account
: {
480 startSynchronization();
483 case R
.id
.action_upload
: {
484 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
487 case R
.id
.action_settings
: {
488 Intent settingsIntent
= new Intent(this, Preferences
.class);
489 startActivity(settingsIntent
);
492 case android
.R
.id
.home
: {
493 FileFragment second
= getSecondFragment();
494 OCFile currentDir
= getCurrentDir();
495 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
496 (second
!= null
&& second
.getFile() != null
)) {
503 retval
= super.onOptionsItemSelected(item
);
508 private void startSynchronization() {
509 Log_OC
.e(TAG
, "Got to start sync");
510 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
511 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
512 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
513 Bundle bundle
= new Bundle();
514 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
515 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
516 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
517 ContentResolver
.requestSync(
519 MainApp
.getAuthority(), bundle
);
521 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
522 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
523 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
524 builder
.setExpedited(true
);
525 builder
.setManual(true
);
527 SyncRequest request
= builder
.build();
528 ContentResolver
.requestSync(request
);
534 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
535 if (itemPosition
!= 0) {
536 String targetPath
= "";
537 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
538 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
540 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
541 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
542 if (targetFolder
!= null
) {
543 browseTo(targetFolder
);
546 // the next operation triggers a new call to this method, but it's necessary to
547 // ensure that the name exposed in the action bar is the current directory when the
548 // user selected it in the navigation list
549 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
550 getSupportActionBar().setSelectedNavigationItem(0);
556 * Called, when the user selected something for uploading
558 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
559 super.onActivityResult(requestCode
, resultCode
, data
);
561 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
562 requestSimpleUpload(data
, resultCode
);
564 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
565 requestMultipleUpload(data
, resultCode
);
570 private void requestMultipleUpload(Intent data
, int resultCode
) {
571 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
572 if (filePaths
!= null
) {
573 String
[] remotePaths
= new String
[filePaths
.length
];
574 String remotePathBase
= "";
575 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
576 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
578 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
579 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
580 for (int j
= 0; j
< remotePaths
.length
; j
++) {
581 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
584 Intent i
= new Intent(this, FileUploader
.class);
585 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
586 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
587 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
588 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
589 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
590 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
594 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
595 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
602 private void requestSimpleUpload(Intent data
, int resultCode
) {
603 String filepath
= null
;
605 Uri selectedImageUri
= data
.getData();
607 String filemanagerstring
= selectedImageUri
.getPath();
608 String selectedImagePath
= getPath(selectedImageUri
);
610 if (selectedImagePath
!= null
)
611 filepath
= selectedImagePath
;
613 filepath
= filemanagerstring
;
615 } catch (Exception e
) {
616 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
620 if (filepath
== null
) {
621 Log_OC
.e(TAG
, "Couldnt resolve path to file");
622 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
628 Intent i
= new Intent(this, FileUploader
.class);
629 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
631 String remotepath
= new String();
632 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
633 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
635 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
636 remotepath
+= OCFile
.PATH_SEPARATOR
;
637 remotepath
+= new File(filepath
).getName();
639 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
640 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
641 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
642 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
643 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
648 public void onBackPressed() {
649 OCFileListFragment listOfFiles
= getListOfFilesFragment();
650 if (mDualPane
|| getSecondFragment() == null
) {
651 if (listOfFiles
!= null
) { // should never be null, indeed
652 if (mDirectories
.getCount() <= 1) {
656 int levelsUp
= listOfFiles
.onBrowseUp();
657 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
662 if (listOfFiles
!= null
) { // should never be null, indeed
663 setFile(listOfFiles
.getCurrentFile());
665 cleanSecondFragment();
670 protected void onSaveInstanceState(Bundle outState
) {
671 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
672 Log_OC
.e(TAG
, "onSaveInstanceState() start");
673 super.onSaveInstanceState(outState
);
674 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
675 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
676 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
677 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
679 Log_OC
.d(TAG
, "onSaveInstanceState() end");
685 protected void onResume() {
687 Log_OC
.e(TAG
, "onResume() start");
689 // Listen for sync messages
690 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
691 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
692 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
693 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
694 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
695 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
696 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
697 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
698 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
700 // Listen for upload messages
701 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
702 mUploadFinishReceiver
= new UploadFinishReceiver();
703 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
705 // Listen for download messages
706 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
707 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
708 mDownloadFinishReceiver
= new DownloadFinishReceiver();
709 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
711 // Listen for messages from the OperationsService
713 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
714 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
715 mOperationsServiceReceiver = new OperationsServiceReceiver();
716 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
719 Log_OC
.d(TAG
, "onResume() end");
724 protected void onPause() {
726 Log_OC
.e(TAG
, "onPause() start");
727 if (mSyncBroadcastReceiver
!= null
) {
728 unregisterReceiver(mSyncBroadcastReceiver
);
729 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
730 mSyncBroadcastReceiver
= null
;
732 if (mUploadFinishReceiver
!= null
) {
733 unregisterReceiver(mUploadFinishReceiver
);
734 mUploadFinishReceiver
= null
;
736 if (mDownloadFinishReceiver
!= null
) {
737 unregisterReceiver(mDownloadFinishReceiver
);
738 mDownloadFinishReceiver
= null
;
741 if (mOperationsServiceReceiver != null) {
742 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
743 mOperationsServiceReceiver = null;
746 Log_OC
.d(TAG
, "onPause() end");
751 protected Dialog
onCreateDialog(int id
) {
752 Dialog dialog
= null
;
753 AlertDialog
.Builder builder
;
755 case DIALOG_SHORT_WAIT
: {
756 ProgressDialog working_dialog
= new ProgressDialog(this);
757 working_dialog
.setMessage(getResources().getString(
758 R
.string
.wait_a_moment
));
759 working_dialog
.setIndeterminate(true
);
760 working_dialog
.setCancelable(false
);
761 dialog
= working_dialog
;
764 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
766 String
[] items
= null
;
768 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
769 getString(R
.string
.actionbar_upload_from_apps
),
770 getString(R
.string
.actionbar_failed_instant_upload
) };
772 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
773 getString(R
.string
.actionbar_upload_from_apps
) };
775 if (InstantUploadActivity
.IS_ENABLED
)
780 builder
= new AlertDialog
.Builder(this);
781 builder
.setTitle(R
.string
.actionbar_upload
);
782 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
783 public void onClick(DialogInterface dialog
, int item
) {
786 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
787 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
788 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
790 // TODO create and handle new fragment
791 // LocalFileListFragment
793 } else if (item
== 1) {
794 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
795 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
796 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
797 ACTION_SELECT_CONTENT_FROM_APPS
);
798 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
799 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
800 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
801 startActivity(action
);
805 dialog
= builder
.create();
808 case DIALOG_CERT_NOT_SAVED
: {
809 builder
= new AlertDialog
.Builder(this);
810 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
811 builder
.setCancelable(false
);
812 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
814 public void onClick(DialogInterface dialog
, int which
) {
818 dialog
= builder
.create();
830 * Translates a content URI of an image to a physical path
832 * @param uri The URI to resolve
833 * @return The path to the image or null if it could not be found
835 public String
getPath(Uri uri
) {
836 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
837 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
838 if (cursor
!= null
) {
839 int column_index
= cursor
840 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
841 cursor
.moveToFirst();
842 return cursor
.getString(column_index
);
848 * Pushes a directory to the drop down list
849 * @param directory to push
850 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
852 public void pushDirname(OCFile directory
) {
853 if(!directory
.isFolder()){
854 throw new IllegalArgumentException("Only directories may be pushed!");
856 mDirectories
.insert(directory
.getFileName(), 0);
861 * Pops a directory name from the drop down list
862 * @return True, unless the stack is empty
864 public boolean popDirname() {
865 mDirectories
.remove(mDirectories
.getItem(0));
866 return !mDirectories
.isEmpty();
869 // Custom array adapter to override text colors
870 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
872 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
876 public View
getView(int position
, View convertView
, ViewGroup parent
) {
877 View v
= super.getView(position
, convertView
, parent
);
879 ((TextView
) v
).setTextColor(getResources().getColorStateList(
880 android
.R
.color
.white
));
882 fixRoot((TextView
) v
);
886 public View
getDropDownView(int position
, View convertView
,
888 View v
= super.getDropDownView(position
, convertView
, parent
);
890 ((TextView
) v
).setTextColor(getResources().getColorStateList(
891 android
.R
.color
.white
));
893 fixRoot((TextView
) v
);
897 private void fixRoot(TextView v
) {
898 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
899 v
.setText(R
.string
.default_display_name_for_root_folder
);
905 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
908 * {@link BroadcastReceiver} to enable syncing feedback in UI
911 public void onReceive(Context context
, Intent intent
) {
913 String event
= intent
.getAction();
914 Log_OC
.d(TAG
, "Received broadcast " + event
);
915 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
916 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
917 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
918 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
922 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
923 mSyncInProgress
= true
;
926 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
927 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
929 if (currentDir
== null
) {
930 // current folder was removed from the server
931 Toast
.makeText( FileDisplayActivity
.this,
932 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
938 if (currentFile
== null
&& !getFile().isFolder()) {
939 // currently selected file was removed in the server, and now we know it
940 cleanSecondFragment();
941 currentFile
= currentDir
;
944 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
945 OCFileListFragment fileListFragment
= getListOfFilesFragment();
946 if (fileListFragment
!= null
) {
947 fileListFragment
.listDirectory(currentDir
);
950 setFile(currentFile
);
953 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
956 if (synchResult != null &&
957 synchResult.isSuccess() &&
958 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
959 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
961 !mRefreshSharesInProgress &&
962 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
969 removeStickyBroadcast(intent
);
970 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
971 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
974 if (synchResult
!= null
) {
975 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
976 mLastSslUntrustedServerResult
= synchResult
;
979 } catch (RuntimeException e
) {
980 // avoid app crashes after changing the serial id of RemoteOperationResult
981 // in owncloud library with broadcast notifications pending to process
982 removeStickyBroadcast(intent
);
988 private class UploadFinishReceiver
extends BroadcastReceiver
{
990 * Once the file upload has finished -> update view
991 * @author David A. Velasco
992 * {@link BroadcastReceiver} to enable upload feedback in UI
995 public void onReceive(Context context
, Intent intent
) {
996 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
997 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
998 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
999 OCFile currentDir
= getCurrentDir();
1000 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1001 if (sameAccount
&& isDescendant
) {
1002 refeshListOfFilesFragment();
1010 * Class waiting for broadcast events from the {@link FielDownloader} service.
1012 * Updates the UI when a download is started or finished, provided that it is relevant for the
1015 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1017 public void onReceive(Context context
, Intent intent
) {
1018 boolean sameAccount
= isSameAccount(context
, intent
);
1019 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1020 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1022 if (sameAccount
&& isDescendant
) {
1023 refeshListOfFilesFragment();
1024 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1027 if (mWaitingToSend
!= null
) {
1028 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1029 if (mWaitingToSend
.isDown()) {
1030 sendDownloadedFile();
1034 removeStickyBroadcast(intent
);
1037 private boolean isDescendant(String downloadedRemotePath
) {
1038 OCFile currentDir
= getCurrentDir();
1039 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1042 private boolean isSameAccount(Context context
, Intent intent
) {
1043 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1044 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1050 * Class waiting for broadcast events from the {@link OperationsService}.
1052 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1053 * operation performed in {@link OperationsService}.
1055 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1056 * probably all the operations associated to the app model.
1058 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1061 public void onReceive(Context context
, Intent intent
) {
1062 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1064 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1065 //mRefreshSharesInProgress = false;
1067 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1068 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1069 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1070 && getStorageManager() != null
1072 refeshListOfFilesFragment();
1074 if ((getSharesResult
!= null
) &&
1075 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1076 mLastSslUntrustedServerResult
= getSharesResult
;
1077 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1080 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1087 public void browseToRoot() {
1088 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1089 if (listOfFiles
!= null
) { // should never be null, indeed
1090 while (mDirectories
.getCount() > 1) {
1093 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1094 listOfFiles
.listDirectory(root
);
1095 setFile(listOfFiles
.getCurrentFile());
1096 startSyncFolderOperation(root
);
1098 cleanSecondFragment();
1102 public void browseTo(OCFile folder
) {
1103 if (folder
== null
|| !folder
.isFolder()) {
1104 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1106 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1107 if (listOfFiles
!= null
) {
1108 setNavigationListWithFolder(folder
);
1109 listOfFiles
.listDirectory(folder
);
1110 setFile(listOfFiles
.getCurrentFile());
1111 startSyncFolderOperation(folder
);
1113 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1115 cleanSecondFragment();
1122 * Updates action bar and second fragment, if in dual pane mode.
1125 public void onBrowsedDownTo(OCFile directory
) {
1126 pushDirname(directory
);
1127 cleanSecondFragment();
1130 startSyncFolderOperation(directory
);
1135 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1137 * @param file Image {@link OCFile} to show.
1140 public void startImagePreview(OCFile file
) {
1141 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1142 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1143 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1144 startActivity(showDetailsIntent
);
1148 * Stars the preview of an already down media {@link OCFile}.
1150 * @param file Media {@link OCFile} to preview.
1151 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1152 * @param autoplay When 'true', the playback will start without user interactions.
1155 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1156 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1157 setSecondFragment(mediaFragment
);
1158 updateFragmentsVisibility(true
);
1159 updateNavigationElementsInActionBar(file
);
1164 * Requests the download of the received {@link OCFile} , updates the UI
1165 * to monitor the download progress and prepares the activity to preview
1166 * or open the file when the download finishes.
1168 * @param file {@link OCFile} to download and preview.
1171 public void startDownloadForPreview(OCFile file
) {
1172 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1173 setSecondFragment(detailFragment
);
1174 mWaitingToPreview
= file
;
1175 requestForDownload();
1176 updateFragmentsVisibility(true
);
1177 updateNavigationElementsInActionBar(file
);
1183 * Shows the information of the {@link OCFile} received as a
1184 * parameter in the second fragment.
1186 * @param file {@link OCFile} whose details will be shown
1189 public void showDetails(OCFile file
) {
1190 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1191 setSecondFragment(detailFragment
);
1192 updateFragmentsVisibility(true
);
1193 updateNavigationElementsInActionBar(file
);
1201 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1202 ActionBar actionBar
= getSupportActionBar();
1203 if (chosenFile
== null
|| mDualPane
) {
1204 // only list of files - set for browsing through folders
1205 OCFile currentDir
= getCurrentDir();
1206 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1207 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1208 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1210 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1212 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1213 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1216 actionBar
.setDisplayHomeAsUpEnabled(true
);
1217 actionBar
.setDisplayShowTitleEnabled(true
);
1218 actionBar
.setTitle(chosenFile
.getFileName());
1219 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1228 public void onFileStateChanged() {
1229 refeshListOfFilesFragment();
1230 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1238 public FileDownloaderBinder
getFileDownloaderBinder() {
1239 return mDownloaderBinder
;
1247 public FileUploaderBinder
getFileUploaderBinder() {
1248 return mUploaderBinder
;
1252 /** Defines callbacks for service binding, passed to bindService() */
1253 private class ListServiceConnection
implements ServiceConnection
{
1256 public void onServiceConnected(ComponentName component
, IBinder service
) {
1257 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1258 Log_OC
.d(TAG
, "Download service connected");
1259 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1260 if (mWaitingToPreview
!= null
) {
1261 requestForDownload();
1264 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1265 Log_OC
.d(TAG
, "Upload service connected");
1266 mUploaderBinder
= (FileUploaderBinder
) service
;
1270 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1271 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1272 if (listOfFiles
!= null
) {
1273 listOfFiles
.listDirectory();
1275 FileFragment secondFragment
= getSecondFragment();
1276 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1277 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1278 detailFragment
.listenForTransferProgress();
1279 detailFragment
.updateFileDetails(false
, false
);
1284 public void onServiceDisconnected(ComponentName component
) {
1285 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1286 Log_OC
.d(TAG
, "Download service disconnected");
1287 mDownloaderBinder
= null
;
1288 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1289 Log_OC
.d(TAG
, "Upload service disconnected");
1290 mUploaderBinder
= null
;
1298 * Launch an intent to request the PIN code to the user before letting him use the app
1300 private void requestPinCode() {
1301 boolean pinStart
= false
;
1302 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1303 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1305 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1306 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1313 public void onSavedCertificate() {
1314 startSyncFolderOperation(getCurrentDir());
1319 public void onFailedSavingCertificate() {
1320 showDialog(DIALOG_CERT_NOT_SAVED
);
1324 public void onCancelCertificate() {
1329 * Updates the view associated to the activity after the finish of some operation over files
1330 * in the current account.
1332 * @param operation Removal operation performed.
1333 * @param result Result of the removal.
1336 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1337 super.onRemoteOperationFinish(operation
, result
);
1339 if (operation
instanceof RemoveFileOperation
) {
1340 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1342 } else if (operation
instanceof RenameFileOperation
) {
1343 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1345 } else if (operation
instanceof SynchronizeFileOperation
) {
1346 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1348 } else if (operation
instanceof CreateFolderOperation
) {
1349 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1351 } else if (operation
instanceof CreateShareOperation
) {
1352 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1354 } else if (operation
instanceof UnshareLinkOperation
) {
1355 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1362 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1363 if (result
.isSuccess()) {
1364 refreshShowDetails();
1365 refeshListOfFilesFragment();
1370 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1371 if (result
.isSuccess()) {
1372 refreshShowDetails();
1373 refeshListOfFilesFragment();
1374 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1375 cleanSecondFragment();
1376 refeshListOfFilesFragment();
1380 private void refreshShowDetails() {
1381 FileFragment details
= getSecondFragment();
1382 if (details
!= null
) {
1383 OCFile file
= details
.getFile();
1385 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1386 if (details
instanceof PreviewMediaFragment
) {
1387 // Refresh OCFile of the fragment
1388 ((PreviewMediaFragment
) details
).updateFile(file
);
1393 invalidateOptionsMenu();
1398 * Updates the view associated to the activity after the finish of an operation trying to remove a
1401 * @param operation Removal operation performed.
1402 * @param result Result of the removal.
1404 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1405 dismissLoadingDialog();
1406 if (result
.isSuccess()) {
1407 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1409 OCFile removedFile
= operation
.getFile();
1410 getSecondFragment();
1411 FileFragment second
= getSecondFragment();
1412 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1413 cleanSecondFragment();
1415 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1416 refeshListOfFilesFragment();
1420 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1422 if (result
.isSslRecoverableException()) {
1423 mLastSslUntrustedServerResult
= result
;
1424 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1430 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1432 * @param operation Creation operation performed.
1433 * @param result Result of the creation.
1435 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1436 if (result
.isSuccess()) {
1437 dismissLoadingDialog();
1438 refeshListOfFilesFragment();
1441 dismissLoadingDialog();
1442 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1443 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1446 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1449 } catch (NotFoundException e
) {
1450 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1458 * Updates the view associated to the activity after the finish of an operation trying to rename a
1461 * @param operation Renaming operation performed.
1462 * @param result Result of the renaming.
1464 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1465 dismissLoadingDialog();
1466 OCFile renamedFile
= operation
.getFile();
1467 if (result
.isSuccess()) {
1469 FileFragment details
= getSecondFragment();
1470 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1471 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1474 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1475 refeshListOfFilesFragment();
1479 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1480 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1482 // TODO throw again the new rename dialog
1483 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1484 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1487 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1489 if (result
.isSslRecoverableException()) {
1490 mLastSslUntrustedServerResult
= result
;
1491 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1498 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1499 dismissLoadingDialog();
1500 OCFile syncedFile
= operation
.getLocalFile();
1501 if (!result
.isSuccess()) {
1502 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1503 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1504 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1505 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1511 if (operation
.transferWasRequested()) {
1512 refeshListOfFilesFragment();
1513 onTransferStateChanged(syncedFile
, true
, true
);
1516 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1527 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1529 FileFragment details
= getSecondFragment();
1530 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1531 if (downloading
|| uploading
) {
1532 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1534 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1541 public void onDismiss(EditNameDialog dialog
) {
1542 if (dialog
.getResult()) {
1543 String newDirectoryName
= dialog
.getNewFilename().trim();
1544 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1545 if (newDirectoryName
.length() > 0) {
1546 String path
= getCurrentDir().getRemotePath();
1549 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1550 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1551 operation
.execute( getAccount(),
1552 FileDisplayActivity
.this,
1553 FileDisplayActivity
.this,
1555 FileDisplayActivity
.this);
1557 showLoadingDialog();
1563 private void requestForDownload() {
1564 Account account
= getAccount();
1565 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1566 Intent i
= new Intent(this, FileDownloader
.class);
1567 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1568 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1574 private OCFile
getCurrentDir() {
1575 OCFile file
= getFile();
1577 if (file
.isFolder()) {
1579 } else if (getStorageManager() != null
) {
1580 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1581 return getStorageManager().getFileByPath(parentPath
);
1587 public void startSyncFolderOperation(OCFile folder
) {
1588 long currentSyncTime
= System
.currentTimeMillis();
1590 mSyncInProgress
= true
;
1592 // perform folder synchronization
1593 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1596 getFileOperationsHelper().isSharedSupported(this),
1597 getStorageManager(),
1599 getApplicationContext()
1601 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1603 setSupportProgressBarIndeterminateVisibility(true
);
1607 private void startGetShares() {
1608 // Get shared files/folders
1609 Intent intent = new Intent(this, OperationsService.class);
1610 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1611 startService(intent);
1613 mRefreshSharesInProgress = true;
1618 * Show untrusted cert dialog
1620 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1621 // Show a dialog with the certificate info
1622 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1623 FragmentManager fm
= getSupportFragmentManager();
1624 FragmentTransaction ft
= fm
.beginTransaction();
1625 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1629 * Requests the download of the received {@link OCFile} , updates the UI
1630 * to monitor the download progress and prepares the activity to send the file
1631 * when the download finishes.
1633 * @param file {@link OCFile} to download and preview.
1636 public void startDownloadForSending(OCFile file
) {
1637 mWaitingToSend
= file
;
1638 requestForDownload(mWaitingToSend
);
1639 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1640 updateFragmentsVisibility(hasSecondFragment
);
1643 private void requestForDownload(OCFile file
) {
1644 Account account
= getAccount();
1645 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1646 Intent i
= new Intent(this, FileDownloader
.class);
1647 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1648 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1653 private void sendDownloadedFile(){
1654 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1655 mWaitingToSend
= null
;