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
.FragmentTransaction
;
46 //import android.support.v4.content.LocalBroadcastManager;
47 import android
.util
.Log
;
48 import android
.view
.View
;
49 import android
.view
.ViewGroup
;
50 import android
.widget
.ArrayAdapter
;
51 import android
.widget
.TextView
;
52 import android
.widget
.Toast
;
54 import com
.actionbarsherlock
.app
.ActionBar
;
55 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
56 import com
.actionbarsherlock
.view
.Menu
;
57 import com
.actionbarsherlock
.view
.MenuInflater
;
58 import com
.actionbarsherlock
.view
.MenuItem
;
59 import com
.actionbarsherlock
.view
.Window
;
60 import com
.owncloud
.android
.MainApp
;
61 import com
.owncloud
.android
.R
;
62 import com
.owncloud
.android
.datamodel
.OCFile
;
63 import com
.owncloud
.android
.files
.services
.FileDownloader
;
64 import com
.owncloud
.android
.files
.services
.FileObserverService
;
65 import com
.owncloud
.android
.files
.services
.FileUploader
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
68 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
70 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
71 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
72 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
.ResultCode
;
73 import com
.owncloud
.android
.operations
.CreateShareOperation
;
74 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
75 import com
.owncloud
.android
.operations
.RenameFileOperation
;
76 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
77 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
78 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
79 import com
.owncloud
.android
.services
.OperationsService
;
80 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
81 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
82 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
83 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
85 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
86 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
87 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
88 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
89 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
91 import com
.owncloud
.android
.utils
.DisplayUtils
;
92 import com
.owncloud
.android
.utils
.Log_OC
;
96 * Displays, what files the user has available in his ownCloud.
98 * @author Bartek Przybylski
99 * @author David A. Velasco
102 public class FileDisplayActivity
extends HookActivity
implements
103 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, EditNameDialogListener
{
105 private ArrayAdapter
<String
> mDirectories
;
107 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
108 private UploadFinishReceiver mUploadFinishReceiver
;
109 private DownloadFinishReceiver mDownloadFinishReceiver
;
110 //private OperationsServiceReceiver mOperationsServiceReceiver;
111 private FileDownloaderBinder mDownloaderBinder
= null
;
112 private FileUploaderBinder mUploaderBinder
= null
;
113 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
114 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
116 private boolean mDualPane
;
117 private View mLeftFragmentContainer
;
118 private View mRightFragmentContainer
;
120 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
121 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
122 private static final String KEY_REFRESH_SHARES_IN_PROGRESS
= "SHARES_IN_PROGRESS";
124 public static final int DIALOG_SHORT_WAIT
= 0;
125 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
126 private static final int DIALOG_SSL_VALIDATOR
= 2;
127 private static final int DIALOG_CERT_NOT_SAVED
= 3;
129 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
131 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
132 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
134 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
136 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
137 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
139 private OCFile mWaitingToPreview
;
141 private boolean mSyncInProgress
= false
;
142 //private boolean mRefreshSharesInProgress = false;
144 private OCFile mWaitingToSend
;
147 protected void onCreate(Bundle savedInstanceState
) {
148 Log_OC
.d(TAG
, "onCreate() start");
149 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
151 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
153 /// bindings to transference services
154 mUploadConnection
= new ListServiceConnection();
155 mDownloadConnection
= new ListServiceConnection();
156 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
157 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
159 // PIN CODE request ; best location is to decide, let's try this first
160 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
162 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
167 Intent observer_intent
= new Intent(this, FileObserverService
.class);
168 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
169 startService(observer_intent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
174 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
175 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
178 mWaitingToPreview
= null
;
179 mSyncInProgress
= false
;
180 //mRefreshSharesInProgress = false;
185 // Inflate and set the layout view
186 setContentView(R
.layout
.files
);
187 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
188 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
189 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
190 if (savedInstanceState
== null
) {
191 createMinFragments();
193 Log_OC
.d(TAG
, "Init the secondFragment again");
195 initFragmentsWithFile();
200 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
201 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
202 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
204 Log_OC
.d(TAG
, "onCreate() end");
208 protected void onStart() {
210 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
211 refeshListOfFilesFragment();
215 protected void onDestroy() {
217 if (mDownloadConnection
!= null
)
218 unbindService(mDownloadConnection
);
219 if (mUploadConnection
!= null
)
220 unbindService(mUploadConnection
);
225 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
228 protected void onAccountSet(boolean stateWasRecovered
) {
229 super.onAccountSet(stateWasRecovered
);
230 if (getAccount() != null
) {
231 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
232 OCFile file
= getFile();
233 // get parent from path
234 String parentPath
= "";
236 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
237 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
238 // get parent from path
239 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
240 if (getStorageManager().getFileByPath(parentPath
) == null
)
241 file
= null
; // not able to know the directory where the file is uploading
243 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
247 // fall back to root folder
248 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
251 setNavigationListWithFolder(file
);
253 if (!stateWasRecovered
) {
254 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
255 initFragmentsWithFile();
256 if (file
.isFolder()) {
257 startSyncFolderOperation(file
);
261 updateFragmentsVisibility(!file
.isFolder());
262 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
268 private void setNavigationListWithFolder(OCFile file
) {
269 mDirectories
.clear();
270 OCFile fileIt
= file
;
272 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
273 if (fileIt
.isFolder()) {
274 mDirectories
.add(fileIt
.getFileName());
276 // get parent from path
277 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
278 fileIt
= getStorageManager().getFileByPath(parentPath
);
280 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
284 private void createMinFragments() {
285 OCFileListFragment listOfFiles
= new OCFileListFragment();
286 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
287 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
288 transaction
.commit();
291 private void initFragmentsWithFile() {
292 if (getAccount() != null
&& getFile() != null
) {
294 OCFileListFragment listOfFiles
= getListOfFilesFragment();
295 if (listOfFiles
!= null
) {
296 listOfFiles
.listDirectory(getCurrentDir());
298 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
302 OCFile file
= getFile();
303 Fragment secondFragment
= chooseInitialSecondFragment(file
);
304 if (secondFragment
!= null
) {
305 setSecondFragment(secondFragment
);
306 updateFragmentsVisibility(true
);
307 updateNavigationElementsInActionBar(file
);
310 cleanSecondFragment();
314 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
315 if (getAccount() == null
) {
316 Log
.wtf(TAG
, "\t account is NULL");
318 if (getFile() == null
) {
319 Log
.wtf(TAG
, "\t file is NULL");
324 private Fragment
chooseInitialSecondFragment(OCFile file
) {
325 Fragment secondFragment
= null
;
326 if (file
!= null
&& !file
.isFolder()) {
327 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
328 && file
.getLastSyncDateForProperties() > 0 // temporal fix
330 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
331 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
332 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
335 secondFragment
= new FileDetailFragment(file
, getAccount());
338 return secondFragment
;
343 * Replaces the second fragment managed by the activity with the received as
346 * Assumes never will be more than two fragments managed at the same time.
348 * @param fragment New second Fragment to set.
350 private void setSecondFragment(Fragment fragment
) {
351 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
352 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
353 transaction
.commit();
357 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
359 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
360 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
362 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
363 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
366 } else if (existsSecondFragment
) {
367 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
368 mLeftFragmentContainer
.setVisibility(View
.GONE
);
370 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
375 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
378 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
379 mRightFragmentContainer
.setVisibility(View
.GONE
);
385 private OCFileListFragment
getListOfFilesFragment() {
386 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
387 if (listOfFiles
!= null
) {
388 return (OCFileListFragment
)listOfFiles
;
390 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
394 protected FileFragment
getSecondFragment() {
395 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
396 if (second
!= null
) {
397 return (FileFragment
)second
;
402 public void cleanSecondFragment() {
403 Fragment second
= getSecondFragment();
404 if (second
!= null
) {
405 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
409 updateFragmentsVisibility(false
);
410 updateNavigationElementsInActionBar(null
);
413 protected void refeshListOfFilesFragment() {
414 OCFileListFragment fileListFragment
= getListOfFilesFragment();
415 if (fileListFragment
!= null
) {
416 fileListFragment
.listDirectory();
420 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
421 FileFragment secondFragment
= getSecondFragment();
422 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
423 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
424 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
425 OCFile fileInFragment
= detailsFragment
.getFile();
426 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
427 // the user browsed to other file ; forget the automatic preview
428 mWaitingToPreview
= null
;
430 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
431 // grant that the right panel updates the progress bar
432 detailsFragment
.listenForTransferProgress();
433 detailsFragment
.updateFileDetails(true
, false
);
435 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
436 // update the right panel
437 boolean detailsFragmentChanged
= false
;
440 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
441 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
442 startMediaPreview(mWaitingToPreview
, 0, true
);
443 detailsFragmentChanged
= true
;
445 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
448 mWaitingToPreview
= null
;
450 if (!detailsFragmentChanged
) {
451 detailsFragment
.updateFileDetails(false
, (success
));
458 public boolean onCreateOptionsMenu(Menu menu
) {
459 MenuInflater inflater
= getSherlock().getMenuInflater();
460 inflater
.inflate(R
.menu
.main_menu
, menu
);
465 public boolean onOptionsItemSelected(MenuItem item
) {
466 boolean retval
= true
;
467 switch (item
.getItemId()) {
468 case R
.id
.action_create_dir
: {
469 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
470 dialog
.show(getSupportFragmentManager(), "createdirdialog");
473 case R
.id
.action_sync_account
: {
474 startSynchronization();
477 case R
.id
.action_upload
: {
478 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
481 case R
.id
.action_settings
: {
482 Intent settingsIntent
= new Intent(this, Preferences
.class);
483 startActivity(settingsIntent
);
486 case android
.R
.id
.home
: {
487 FileFragment second
= getSecondFragment();
488 OCFile currentDir
= getCurrentDir();
489 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
490 (second
!= null
&& second
.getFile() != null
)) {
497 retval
= super.onOptionsItemSelected(item
);
502 private void startSynchronization() {
503 Log_OC
.e(TAG
, "Got to start sync");
504 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
505 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
506 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
507 Bundle bundle
= new Bundle();
508 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
509 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
510 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
511 ContentResolver
.requestSync(
513 MainApp
.getAuthority(), bundle
);
515 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
516 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
517 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
518 builder
.setExpedited(true
);
519 builder
.setManual(true
);
521 SyncRequest request
= builder
.build();
522 ContentResolver
.requestSync(request
);
528 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
529 if (itemPosition
!= 0) {
530 String targetPath
= "";
531 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
532 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
534 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
535 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
536 if (targetFolder
!= null
) {
537 browseTo(targetFolder
);
540 // the next operation triggers a new call to this method, but it's necessary to
541 // ensure that the name exposed in the action bar is the current directory when the
542 // user selected it in the navigation list
543 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
544 getSupportActionBar().setSelectedNavigationItem(0);
550 * Called, when the user selected something for uploading
552 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
553 super.onActivityResult(requestCode
, resultCode
, data
);
555 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
556 requestSimpleUpload(data
, resultCode
);
558 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
559 requestMultipleUpload(data
, resultCode
);
564 private void requestMultipleUpload(Intent data
, int resultCode
) {
565 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
566 if (filePaths
!= null
) {
567 String
[] remotePaths
= new String
[filePaths
.length
];
568 String remotePathBase
= "";
569 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
570 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
572 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
573 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
574 for (int j
= 0; j
< remotePaths
.length
; j
++) {
575 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
578 Intent i
= new Intent(this, FileUploader
.class);
579 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
580 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
581 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
582 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
583 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
584 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
588 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
589 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
596 private void requestSimpleUpload(Intent data
, int resultCode
) {
597 String filepath
= null
;
599 Uri selectedImageUri
= data
.getData();
601 String filemanagerstring
= selectedImageUri
.getPath();
602 String selectedImagePath
= getPath(selectedImageUri
);
604 if (selectedImagePath
!= null
)
605 filepath
= selectedImagePath
;
607 filepath
= filemanagerstring
;
609 } catch (Exception e
) {
610 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
614 if (filepath
== null
) {
615 Log_OC
.e(TAG
, "Couldnt resolve path to file");
616 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
622 Intent i
= new Intent(this, FileUploader
.class);
623 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
625 String remotepath
= new String();
626 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
627 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
629 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
630 remotepath
+= OCFile
.PATH_SEPARATOR
;
631 remotepath
+= new File(filepath
).getName();
633 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
634 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
635 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
636 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
637 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
642 public void onBackPressed() {
643 OCFileListFragment listOfFiles
= getListOfFilesFragment();
644 if (mDualPane
|| getSecondFragment() == null
) {
645 if (listOfFiles
!= null
) { // should never be null, indeed
646 if (mDirectories
.getCount() <= 1) {
650 int levelsUp
= listOfFiles
.onBrowseUp();
651 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
656 if (listOfFiles
!= null
) { // should never be null, indeed
657 setFile(listOfFiles
.getCurrentFile());
659 cleanSecondFragment();
664 protected void onSaveInstanceState(Bundle outState
) {
665 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
666 Log_OC
.e(TAG
, "onSaveInstanceState() start");
667 super.onSaveInstanceState(outState
);
668 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
669 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
670 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
672 Log_OC
.d(TAG
, "onSaveInstanceState() end");
678 protected void onResume() {
680 Log_OC
.e(TAG
, "onResume() start");
682 // Listen for sync messages
683 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
684 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
685 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED
);
686 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
687 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
688 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
689 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
690 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
691 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
693 // Listen for upload messages
694 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
695 mUploadFinishReceiver
= new UploadFinishReceiver();
696 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
698 // Listen for download messages
699 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
700 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
701 mDownloadFinishReceiver
= new DownloadFinishReceiver();
702 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
704 // Listen for messages from the OperationsService
706 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
707 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
708 mOperationsServiceReceiver = new OperationsServiceReceiver();
709 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
712 Log_OC
.d(TAG
, "onResume() end");
717 protected void onPause() {
719 Log_OC
.e(TAG
, "onPause() start");
720 if (mSyncBroadcastReceiver
!= null
) {
721 unregisterReceiver(mSyncBroadcastReceiver
);
722 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
723 mSyncBroadcastReceiver
= null
;
725 if (mUploadFinishReceiver
!= null
) {
726 unregisterReceiver(mUploadFinishReceiver
);
727 mUploadFinishReceiver
= null
;
729 if (mDownloadFinishReceiver
!= null
) {
730 unregisterReceiver(mDownloadFinishReceiver
);
731 mDownloadFinishReceiver
= null
;
734 if (mOperationsServiceReceiver != null) {
735 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
736 mOperationsServiceReceiver = null;
739 Log_OC
.d(TAG
, "onPause() end");
744 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
745 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
746 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
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_SSL_VALIDATOR
: {
810 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
813 case DIALOG_CERT_NOT_SAVED
: {
814 builder
= new AlertDialog
.Builder(this);
815 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
816 builder
.setCancelable(false
);
817 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
819 public void onClick(DialogInterface dialog
, int which
) {
823 dialog
= builder
.create();
835 * Translates a content URI of an image to a physical path
837 * @param uri The URI to resolve
838 * @return The path to the image or null if it could not be found
840 public String
getPath(Uri uri
) {
841 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
842 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
843 if (cursor
!= null
) {
844 int column_index
= cursor
845 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
846 cursor
.moveToFirst();
847 return cursor
.getString(column_index
);
853 * Pushes a directory to the drop down list
854 * @param directory to push
855 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
857 public void pushDirname(OCFile directory
) {
858 if(!directory
.isFolder()){
859 throw new IllegalArgumentException("Only directories may be pushed!");
861 mDirectories
.insert(directory
.getFileName(), 0);
866 * Pops a directory name from the drop down list
867 * @return True, unless the stack is empty
869 public boolean popDirname() {
870 mDirectories
.remove(mDirectories
.getItem(0));
871 return !mDirectories
.isEmpty();
874 // Custom array adapter to override text colors
875 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
877 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
881 public View
getView(int position
, View convertView
, ViewGroup parent
) {
882 View v
= super.getView(position
, convertView
, parent
);
884 ((TextView
) v
).setTextColor(getResources().getColorStateList(
885 android
.R
.color
.white
));
887 fixRoot((TextView
) v
);
891 public View
getDropDownView(int position
, View convertView
,
893 View v
= super.getDropDownView(position
, convertView
, parent
);
895 ((TextView
) v
).setTextColor(getResources().getColorStateList(
896 android
.R
.color
.white
));
898 fixRoot((TextView
) v
);
902 private void fixRoot(TextView v
) {
903 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
904 v
.setText(R
.string
.default_display_name_for_root_folder
);
910 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
913 * {@link BroadcastReceiver} to enable syncing feedback in UI
916 public void onReceive(Context context
, Intent intent
) {
917 String event
= intent
.getAction();
918 Log_OC
.d(TAG
, "Received broadcast " + event
);
919 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
920 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
921 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
922 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
926 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
927 mSyncInProgress
= true
;
930 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
931 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
933 if (currentDir
== null
) {
934 // current folder was removed from the server
935 Toast
.makeText( FileDisplayActivity
.this,
936 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
942 if (currentFile
== null
&& !getFile().isFolder()) {
943 // currently selected file was removed in the server, and now we know it
944 cleanSecondFragment();
945 currentFile
= currentDir
;
948 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
949 OCFileListFragment fileListFragment
= getListOfFilesFragment();
950 if (fileListFragment
!= null
) {
951 fileListFragment
.listDirectory(currentDir
);
954 setFile(currentFile
);
957 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
960 if (synchResult != null &&
961 synchResult.isSuccess() &&
962 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
963 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
965 !mRefreshSharesInProgress &&
966 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
973 removeStickyBroadcast(intent
);
974 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
975 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
978 if (synchResult
!= null
) {
979 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
980 mLastSslUntrustedServerResult
= synchResult
;
981 showDialog(DIALOG_SSL_VALIDATOR
);
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
&& mWaitingToSend
.isDown()) {
1029 sendDownloadedFile();
1032 removeStickyBroadcast(intent
);
1035 private boolean isDescendant(String downloadedRemotePath
) {
1036 OCFile currentDir
= getCurrentDir();
1037 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1040 private boolean isSameAccount(Context context
, Intent intent
) {
1041 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1042 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1048 * Class waiting for broadcast events from the {@link OperationsService}.
1050 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1051 * operation performed in {@link OperationsService}.
1053 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1054 * probably all the operations associated to the app model.
1056 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1059 public void onReceive(Context context
, Intent intent
) {
1060 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1062 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1063 //mRefreshSharesInProgress = false;
1065 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1066 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1067 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1068 && getStorageManager() != null
1070 refeshListOfFilesFragment();
1072 if ((getSharesResult
!= null
) &&
1073 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1074 mLastSslUntrustedServerResult
= getSharesResult
;
1075 showDialog(DIALOG_SSL_VALIDATOR
);
1078 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1085 public void browseToRoot() {
1086 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1087 if (listOfFiles
!= null
) { // should never be null, indeed
1088 while (mDirectories
.getCount() > 1) {
1091 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1092 listOfFiles
.listDirectory(root
);
1093 setFile(listOfFiles
.getCurrentFile());
1094 startSyncFolderOperation(root
);
1096 cleanSecondFragment();
1100 public void browseTo(OCFile folder
) {
1101 if (folder
== null
|| !folder
.isFolder()) {
1102 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1104 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1105 if (listOfFiles
!= null
) {
1106 setNavigationListWithFolder(folder
);
1107 listOfFiles
.listDirectory(folder
);
1108 setFile(listOfFiles
.getCurrentFile());
1109 startSyncFolderOperation(folder
);
1111 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1113 cleanSecondFragment();
1120 * Updates action bar and second fragment, if in dual pane mode.
1123 public void onBrowsedDownTo(OCFile directory
) {
1124 pushDirname(directory
);
1125 cleanSecondFragment();
1128 startSyncFolderOperation(directory
);
1133 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1135 * @param file Image {@link OCFile} to show.
1138 public void startImagePreview(OCFile file
) {
1139 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1140 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1141 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1142 startActivity(showDetailsIntent
);
1146 * Stars the preview of an already down media {@link OCFile}.
1148 * @param file Media {@link OCFile} to preview.
1149 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1150 * @param autoplay When 'true', the playback will start without user interactions.
1153 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1154 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1155 setSecondFragment(mediaFragment
);
1156 updateFragmentsVisibility(true
);
1157 updateNavigationElementsInActionBar(file
);
1162 * Requests the download of the received {@link OCFile} , updates the UI
1163 * to monitor the download progress and prepares the activity to preview
1164 * or open the file when the download finishes.
1166 * @param file {@link OCFile} to download and preview.
1169 public void startDownloadForPreview(OCFile file
) {
1170 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1171 setSecondFragment(detailFragment
);
1172 mWaitingToPreview
= file
;
1173 requestForDownload();
1174 updateFragmentsVisibility(true
);
1175 updateNavigationElementsInActionBar(file
);
1181 * Shows the information of the {@link OCFile} received as a
1182 * parameter in the second fragment.
1184 * @param file {@link OCFile} whose details will be shown
1187 public void showDetails(OCFile file
) {
1188 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1189 setSecondFragment(detailFragment
);
1190 updateFragmentsVisibility(true
);
1191 updateNavigationElementsInActionBar(file
);
1199 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1200 ActionBar actionBar
= getSupportActionBar();
1201 if (chosenFile
== null
|| mDualPane
) {
1202 // only list of files - set for browsing through folders
1203 OCFile currentDir
= getCurrentDir();
1204 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1205 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1206 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1208 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1210 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1211 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1214 actionBar
.setDisplayHomeAsUpEnabled(true
);
1215 actionBar
.setDisplayShowTitleEnabled(true
);
1216 actionBar
.setTitle(chosenFile
.getFileName());
1217 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1226 public void onFileStateChanged() {
1227 refeshListOfFilesFragment();
1228 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1236 public FileDownloaderBinder
getFileDownloaderBinder() {
1237 return mDownloaderBinder
;
1245 public FileUploaderBinder
getFileUploaderBinder() {
1246 return mUploaderBinder
;
1250 /** Defines callbacks for service binding, passed to bindService() */
1251 private class ListServiceConnection
implements ServiceConnection
{
1254 public void onServiceConnected(ComponentName component
, IBinder service
) {
1255 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1256 Log_OC
.d(TAG
, "Download service connected");
1257 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1258 if (mWaitingToPreview
!= null
) {
1259 requestForDownload();
1262 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1263 Log_OC
.d(TAG
, "Upload service connected");
1264 mUploaderBinder
= (FileUploaderBinder
) service
;
1268 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1269 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1270 if (listOfFiles
!= null
) {
1271 listOfFiles
.listDirectory();
1273 FileFragment secondFragment
= getSecondFragment();
1274 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1275 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1276 detailFragment
.listenForTransferProgress();
1277 detailFragment
.updateFileDetails(false
, false
);
1282 public void onServiceDisconnected(ComponentName component
) {
1283 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1284 Log_OC
.d(TAG
, "Download service disconnected");
1285 mDownloaderBinder
= null
;
1286 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1287 Log_OC
.d(TAG
, "Upload service disconnected");
1288 mUploaderBinder
= null
;
1296 * Launch an intent to request the PIN code to the user before letting him use the app
1298 private void requestPinCode() {
1299 boolean pinStart
= false
;
1300 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1301 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1303 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1304 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1311 public void onSavedCertificate() {
1312 startSyncFolderOperation(getCurrentDir());
1317 public void onFailedSavingCertificate() {
1318 showDialog(DIALOG_CERT_NOT_SAVED
);
1323 * Updates the view associated to the activity after the finish of some operation over files
1324 * in the current account.
1326 * @param operation Removal operation performed.
1327 * @param result Result of the removal.
1330 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1331 super.onRemoteOperationFinish(operation
, result
);
1333 if (operation
instanceof RemoveFileOperation
) {
1334 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1336 } else if (operation
instanceof RenameFileOperation
) {
1337 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1339 } else if (operation
instanceof SynchronizeFileOperation
) {
1340 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1342 } else if (operation
instanceof CreateFolderOperation
) {
1343 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1345 } else if (operation
instanceof CreateShareOperation
) {
1346 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1348 } else if (operation
instanceof UnshareLinkOperation
) {
1349 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1356 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1357 if (result
.isSuccess()) {
1358 refreshShowDetails();
1359 refeshListOfFilesFragment();
1364 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1365 if (result
.isSuccess()) {
1366 refreshShowDetails();
1367 refeshListOfFilesFragment();
1368 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1369 cleanSecondFragment();
1370 refeshListOfFilesFragment();
1374 private void refreshShowDetails() {
1375 FileFragment details
= getSecondFragment();
1376 if (details
!= null
) {
1377 OCFile file
= details
.getFile();
1379 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1380 if (details
instanceof PreviewMediaFragment
) {
1381 // Refresh OCFile of the fragment
1382 ((PreviewMediaFragment
) details
).updateFile(file
);
1387 invalidateOptionsMenu();
1392 * Updates the view associated to the activity after the finish of an operation trying to remove a
1395 * @param operation Removal operation performed.
1396 * @param result Result of the removal.
1398 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1399 dismissLoadingDialog();
1400 if (result
.isSuccess()) {
1401 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1403 OCFile removedFile
= operation
.getFile();
1404 getSecondFragment();
1405 FileFragment second
= getSecondFragment();
1406 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1407 cleanSecondFragment();
1409 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1410 refeshListOfFilesFragment();
1414 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1416 if (result
.isSslRecoverableException()) {
1417 mLastSslUntrustedServerResult
= result
;
1418 showDialog(DIALOG_SSL_VALIDATOR
);
1424 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1426 * @param operation Creation operation performed.
1427 * @param result Result of the creation.
1429 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1430 if (result
.isSuccess()) {
1431 dismissLoadingDialog();
1432 refeshListOfFilesFragment();
1435 dismissLoadingDialog();
1436 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1437 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1440 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1443 } catch (NotFoundException e
) {
1444 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1452 * Updates the view associated to the activity after the finish of an operation trying to rename a
1455 * @param operation Renaming operation performed.
1456 * @param result Result of the renaming.
1458 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1459 dismissLoadingDialog();
1460 OCFile renamedFile
= operation
.getFile();
1461 if (result
.isSuccess()) {
1463 FileFragment details
= getSecondFragment();
1464 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1465 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1468 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1469 refeshListOfFilesFragment();
1473 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1474 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1476 // TODO throw again the new rename dialog
1477 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1478 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1481 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1483 if (result
.isSslRecoverableException()) {
1484 mLastSslUntrustedServerResult
= result
;
1485 showDialog(DIALOG_SSL_VALIDATOR
);
1492 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1493 dismissLoadingDialog();
1494 OCFile syncedFile
= operation
.getLocalFile();
1495 if (!result
.isSuccess()) {
1496 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1497 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1498 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1499 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1505 if (operation
.transferWasRequested()) {
1506 refeshListOfFilesFragment();
1507 onTransferStateChanged(syncedFile
, true
, true
);
1510 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1521 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1523 FileFragment details
= getSecondFragment();
1524 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1525 if (downloading
|| uploading
) {
1526 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1528 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1535 public void onDismiss(EditNameDialog dialog
) {
1536 if (dialog
.getResult()) {
1537 String newDirectoryName
= dialog
.getNewFilename().trim();
1538 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1539 if (newDirectoryName
.length() > 0) {
1540 String path
= getCurrentDir().getRemotePath();
1543 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1544 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1545 operation
.execute( getAccount(),
1546 FileDisplayActivity
.this,
1547 FileDisplayActivity
.this,
1549 FileDisplayActivity
.this);
1551 showLoadingDialog();
1557 private void requestForDownload() {
1558 Account account
= getAccount();
1559 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1560 Intent i
= new Intent(this, FileDownloader
.class);
1561 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1562 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1568 private OCFile
getCurrentDir() {
1569 OCFile file
= getFile();
1571 if (file
.isFolder()) {
1573 } else if (getStorageManager() != null
) {
1574 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1575 return getStorageManager().getFileByPath(parentPath
);
1581 public void startSyncFolderOperation(OCFile folder
) {
1582 long currentSyncTime
= System
.currentTimeMillis();
1584 mSyncInProgress
= true
;
1586 // perform folder synchronization
1587 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1590 getFileOperationsHelper().isSharedSupported(this),
1591 getStorageManager(),
1593 getApplicationContext()
1595 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1597 setSupportProgressBarIndeterminateVisibility(true
);
1601 private void startGetShares() {
1602 // Get shared files/folders
1603 Intent intent = new Intent(this, OperationsService.class);
1604 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1605 startService(intent);
1607 mRefreshSharesInProgress = true;
1612 * Requests the download of the received {@link OCFile} , updates the UI
1613 * to monitor the download progress and prepares the activity to send the file
1614 * when the download finishes.
1616 * @param file {@link OCFile} to download and preview.
1619 public void startDownloadForSending(OCFile file
) {
1620 mWaitingToSend
= file
;
1621 requestForDownload(mWaitingToSend
);
1622 updateFragmentsVisibility(true
);
1625 private void requestForDownload(OCFile file
) {
1626 Account account
= getAccount();
1627 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1628 Intent i
= new Intent(this, FileDownloader
.class);
1629 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1630 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1635 private void sendDownloadedFile(){
1636 dismissLoadingDialog();
1637 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1638 mWaitingToSend
= null
;