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
.PreviewImageFragment
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
92 import com
.owncloud
.android
.utils
.DisplayUtils
;
93 import com
.owncloud
.android
.utils
.Log_OC
;
97 * Displays, what files the user has available in his ownCloud.
99 * @author Bartek Przybylski
100 * @author David A. Velasco
103 public class FileDisplayActivity
extends HookActivity
implements
104 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, EditNameDialogListener
{
106 private ArrayAdapter
<String
> mDirectories
;
108 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
109 private UploadFinishReceiver mUploadFinishReceiver
;
110 private DownloadFinishReceiver mDownloadFinishReceiver
;
111 //private OperationsServiceReceiver mOperationsServiceReceiver;
112 private FileDownloaderBinder mDownloaderBinder
= null
;
113 private FileUploaderBinder mUploaderBinder
= null
;
114 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
115 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
117 private boolean mDualPane
;
118 private View mLeftFragmentContainer
;
119 private View mRightFragmentContainer
;
121 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
122 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
123 private static final String KEY_REFRESH_SHARES_IN_PROGRESS
= "SHARES_IN_PROGRESS";
125 public static final int DIALOG_SHORT_WAIT
= 0;
126 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
127 private static final int DIALOG_SSL_VALIDATOR
= 2;
128 private static final int DIALOG_CERT_NOT_SAVED
= 3;
130 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
132 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
133 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
135 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
137 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
138 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
140 private OCFile mWaitingToPreview
;
142 private boolean mSyncInProgress
= false
;
143 //private boolean mRefreshSharesInProgress = false;
146 protected void onCreate(Bundle savedInstanceState
) {
147 Log_OC
.d(TAG
, "onCreate() start");
148 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
150 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
152 /// bindings to transference services
153 mUploadConnection
= new ListServiceConnection();
154 mDownloadConnection
= new ListServiceConnection();
155 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
156 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
158 // PIN CODE request ; best location is to decide, let's try this first
159 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
161 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
166 Intent observer_intent
= new Intent(this, FileObserverService
.class);
167 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
168 startService(observer_intent
);
170 /// Load of saved instance state
171 if(savedInstanceState
!= null
) {
172 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
173 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
174 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
177 mWaitingToPreview
= null
;
178 mSyncInProgress
= false
;
179 //mRefreshSharesInProgress = false;
184 // Inflate and set the layout view
185 setContentView(R
.layout
.files
);
186 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
187 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
188 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
189 if (savedInstanceState
== null
) {
190 createMinFragments();
192 Log_OC
.d(TAG
, "Init the secondFragment again");
194 initFragmentsWithFile();
199 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
200 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
201 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
203 Log_OC
.d(TAG
, "onCreate() end");
207 protected void onStart() {
209 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
210 refeshListOfFilesFragment();
214 protected void onDestroy() {
216 if (mDownloadConnection
!= null
)
217 unbindService(mDownloadConnection
);
218 if (mUploadConnection
!= null
)
219 unbindService(mUploadConnection
);
224 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
227 protected void onAccountSet(boolean stateWasRecovered
) {
228 super.onAccountSet(stateWasRecovered
);
229 if (getAccount() != null
) {
230 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
231 OCFile file
= getFile();
232 // get parent from path
233 String parentPath
= "";
235 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
236 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
237 // get parent from path
238 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
239 if (getStorageManager().getFileByPath(parentPath
) == null
)
240 file
= null
; // not able to know the directory where the file is uploading
242 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
246 // fall back to root folder
247 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
250 setNavigationListWithFolder(file
);
252 if (!stateWasRecovered
) {
253 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
254 initFragmentsWithFile();
255 if (file
.isFolder()) {
256 startSyncFolderOperation(file
);
260 updateFragmentsVisibility(!file
.isFolder());
261 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
267 private void setNavigationListWithFolder(OCFile file
) {
268 mDirectories
.clear();
269 OCFile fileIt
= file
;
271 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
272 if (fileIt
.isFolder()) {
273 mDirectories
.add(fileIt
.getFileName());
275 // get parent from path
276 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
277 fileIt
= getStorageManager().getFileByPath(parentPath
);
279 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
283 private void createMinFragments() {
284 OCFileListFragment listOfFiles
= new OCFileListFragment();
285 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
286 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
287 transaction
.commit();
290 private void initFragmentsWithFile() {
291 if (getAccount() != null
&& getFile() != null
) {
293 OCFileListFragment listOfFiles
= getListOfFilesFragment();
294 if (listOfFiles
!= null
) {
295 listOfFiles
.listDirectory(getCurrentDir());
297 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
301 OCFile file
= getFile();
302 Fragment secondFragment
= chooseInitialSecondFragment(file
);
303 if (secondFragment
!= null
) {
304 setSecondFragment(secondFragment
);
305 updateFragmentsVisibility(true
);
306 updateNavigationElementsInActionBar(file
);
309 cleanSecondFragment();
313 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
314 if (getAccount() == null
) {
315 Log
.wtf(TAG
, "\t account is NULL");
317 if (getFile() == null
) {
318 Log
.wtf(TAG
, "\t file is NULL");
323 private Fragment
chooseInitialSecondFragment(OCFile file
) {
324 Fragment secondFragment
= null
;
325 if (file
!= null
&& !file
.isFolder()) {
326 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
327 && file
.getLastSyncDateForProperties() > 0 // temporal fix
329 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
330 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
331 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
334 secondFragment
= new FileDetailFragment(file
, getAccount());
337 return secondFragment
;
342 * Replaces the second fragment managed by the activity with the received as
345 * Assumes never will be more than two fragments managed at the same time.
347 * @param fragment New second Fragment to set.
349 private void setSecondFragment(Fragment fragment
) {
350 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
351 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
352 transaction
.commit();
356 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
358 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
359 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
361 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
362 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
365 } else if (existsSecondFragment
) {
366 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
367 mLeftFragmentContainer
.setVisibility(View
.GONE
);
369 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
374 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
377 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
378 mRightFragmentContainer
.setVisibility(View
.GONE
);
384 private OCFileListFragment
getListOfFilesFragment() {
385 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
386 if (listOfFiles
!= null
) {
387 return (OCFileListFragment
)listOfFiles
;
389 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
393 protected FileFragment
getSecondFragment() {
394 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
395 if (second
!= null
) {
396 return (FileFragment
)second
;
401 public void cleanSecondFragment() {
402 Fragment second
= getSecondFragment();
403 if (second
!= null
) {
404 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
408 updateFragmentsVisibility(false
);
409 updateNavigationElementsInActionBar(null
);
412 protected void refeshListOfFilesFragment() {
413 OCFileListFragment fileListFragment
= getListOfFilesFragment();
414 if (fileListFragment
!= null
) {
415 fileListFragment
.listDirectory();
419 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
420 FileFragment secondFragment
= getSecondFragment();
421 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
422 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
423 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
424 OCFile fileInFragment
= detailsFragment
.getFile();
425 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
426 // the user browsed to other file ; forget the automatic preview
427 mWaitingToPreview
= null
;
429 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
430 // grant that the right panel updates the progress bar
431 detailsFragment
.listenForTransferProgress();
432 detailsFragment
.updateFileDetails(true
, false
);
434 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
435 // update the right panel
436 boolean detailsFragmentChanged
= false
;
439 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
440 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
441 startMediaPreview(mWaitingToPreview
, 0, true
);
442 detailsFragmentChanged
= true
;
444 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
447 mWaitingToPreview
= null
;
449 if (!detailsFragmentChanged
) {
450 detailsFragment
.updateFileDetails(false
, (success
));
457 public boolean onCreateOptionsMenu(Menu menu
) {
458 MenuInflater inflater
= getSherlock().getMenuInflater();
459 inflater
.inflate(R
.menu
.main_menu
, menu
);
464 public boolean onOptionsItemSelected(MenuItem item
) {
465 boolean retval
= true
;
466 switch (item
.getItemId()) {
467 case R
.id
.action_create_dir
: {
468 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
469 dialog
.show(getSupportFragmentManager(), "createdirdialog");
472 case R
.id
.action_sync_account
: {
473 startSynchronization();
476 case R
.id
.action_upload
: {
477 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
480 case R
.id
.action_settings
: {
481 Intent settingsIntent
= new Intent(this, Preferences
.class);
482 startActivity(settingsIntent
);
485 case android
.R
.id
.home
: {
486 FileFragment second
= getSecondFragment();
487 OCFile currentDir
= getCurrentDir();
488 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
489 (second
!= null
&& second
.getFile() != null
)) {
496 retval
= super.onOptionsItemSelected(item
);
501 private void startSynchronization() {
502 Log_OC
.e(TAG
, "Got to start sync");
503 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
504 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
505 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
506 Bundle bundle
= new Bundle();
507 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
508 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
509 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
510 ContentResolver
.requestSync(
512 MainApp
.getAuthority(), bundle
);
514 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
515 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
516 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
517 builder
.setExpedited(true
);
518 builder
.setManual(true
);
520 SyncRequest request
= builder
.build();
521 ContentResolver
.requestSync(request
);
527 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
528 if (itemPosition
!= 0) {
529 String targetPath
= "";
530 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
531 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
533 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
534 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
535 if (targetFolder
!= null
) {
536 browseTo(targetFolder
);
539 // the next operation triggers a new call to this method, but it's necessary to
540 // ensure that the name exposed in the action bar is the current directory when the
541 // user selected it in the navigation list
542 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
543 getSupportActionBar().setSelectedNavigationItem(0);
549 * Called, when the user selected something for uploading
551 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
552 super.onActivityResult(requestCode
, resultCode
, data
);
554 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
555 requestSimpleUpload(data
, resultCode
);
557 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
558 requestMultipleUpload(data
, resultCode
);
563 private void requestMultipleUpload(Intent data
, int resultCode
) {
564 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
565 if (filePaths
!= null
) {
566 String
[] remotePaths
= new String
[filePaths
.length
];
567 String remotePathBase
= "";
568 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
569 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
571 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
572 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
573 for (int j
= 0; j
< remotePaths
.length
; j
++) {
574 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
577 Intent i
= new Intent(this, FileUploader
.class);
578 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
579 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
580 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
581 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
582 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
583 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
587 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
588 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
595 private void requestSimpleUpload(Intent data
, int resultCode
) {
596 String filepath
= null
;
598 Uri selectedImageUri
= data
.getData();
600 String filemanagerstring
= selectedImageUri
.getPath();
601 String selectedImagePath
= getPath(selectedImageUri
);
603 if (selectedImagePath
!= null
)
604 filepath
= selectedImagePath
;
606 filepath
= filemanagerstring
;
608 } catch (Exception e
) {
609 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
613 if (filepath
== null
) {
614 Log_OC
.e(TAG
, "Couldnt resolve path to file");
615 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
621 Intent i
= new Intent(this, FileUploader
.class);
622 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
624 String remotepath
= new String();
625 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
626 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
628 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
629 remotepath
+= OCFile
.PATH_SEPARATOR
;
630 remotepath
+= new File(filepath
).getName();
632 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
633 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
634 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
635 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
636 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
641 public void onBackPressed() {
642 OCFileListFragment listOfFiles
= getListOfFilesFragment();
643 if (mDualPane
|| getSecondFragment() == null
) {
644 if (listOfFiles
!= null
) { // should never be null, indeed
645 if (mDirectories
.getCount() <= 1) {
649 int levelsUp
= listOfFiles
.onBrowseUp();
650 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
655 if (listOfFiles
!= null
) { // should never be null, indeed
656 setFile(listOfFiles
.getCurrentFile());
658 cleanSecondFragment();
663 protected void onSaveInstanceState(Bundle outState
) {
664 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
665 Log_OC
.e(TAG
, "onSaveInstanceState() start");
666 super.onSaveInstanceState(outState
);
667 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
668 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
669 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
671 Log_OC
.d(TAG
, "onSaveInstanceState() end");
677 protected void onResume() {
679 Log_OC
.e(TAG
, "onResume() start");
681 // Listen for sync messages
682 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
683 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
684 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED
);
685 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
686 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
687 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
688 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
689 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
690 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
692 // Listen for upload messages
693 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
694 mUploadFinishReceiver
= new UploadFinishReceiver();
695 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
697 // Listen for download messages
698 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
699 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
700 mDownloadFinishReceiver
= new DownloadFinishReceiver();
701 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
703 // Listen for messages from the OperationsService
705 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
706 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
707 mOperationsServiceReceiver = new OperationsServiceReceiver();
708 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
711 Log_OC
.d(TAG
, "onResume() end");
716 protected void onPause() {
718 Log_OC
.e(TAG
, "onPause() start");
719 if (mSyncBroadcastReceiver
!= null
) {
720 unregisterReceiver(mSyncBroadcastReceiver
);
721 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
722 mSyncBroadcastReceiver
= null
;
724 if (mUploadFinishReceiver
!= null
) {
725 unregisterReceiver(mUploadFinishReceiver
);
726 mUploadFinishReceiver
= null
;
728 if (mDownloadFinishReceiver
!= null
) {
729 unregisterReceiver(mDownloadFinishReceiver
);
730 mDownloadFinishReceiver
= null
;
733 if (mOperationsServiceReceiver != null) {
734 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
735 mOperationsServiceReceiver = null;
738 Log_OC
.d(TAG
, "onPause() end");
743 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
744 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
745 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
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_SSL_VALIDATOR
: {
809 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
812 case DIALOG_CERT_NOT_SAVED
: {
813 builder
= new AlertDialog
.Builder(this);
814 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
815 builder
.setCancelable(false
);
816 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
818 public void onClick(DialogInterface dialog
, int which
) {
822 dialog
= builder
.create();
834 * Translates a content URI of an image to a physical path
836 * @param uri The URI to resolve
837 * @return The path to the image or null if it could not be found
839 public String
getPath(Uri uri
) {
840 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
841 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
842 if (cursor
!= null
) {
843 int column_index
= cursor
844 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
845 cursor
.moveToFirst();
846 return cursor
.getString(column_index
);
852 * Pushes a directory to the drop down list
853 * @param directory to push
854 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
856 public void pushDirname(OCFile directory
) {
857 if(!directory
.isFolder()){
858 throw new IllegalArgumentException("Only directories may be pushed!");
860 mDirectories
.insert(directory
.getFileName(), 0);
865 * Pops a directory name from the drop down list
866 * @return True, unless the stack is empty
868 public boolean popDirname() {
869 mDirectories
.remove(mDirectories
.getItem(0));
870 return !mDirectories
.isEmpty();
873 // Custom array adapter to override text colors
874 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
876 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
880 public View
getView(int position
, View convertView
, ViewGroup parent
) {
881 View v
= super.getView(position
, convertView
, parent
);
883 ((TextView
) v
).setTextColor(getResources().getColorStateList(
884 android
.R
.color
.white
));
886 fixRoot((TextView
) v
);
890 public View
getDropDownView(int position
, View convertView
,
892 View v
= super.getDropDownView(position
, convertView
, parent
);
894 ((TextView
) v
).setTextColor(getResources().getColorStateList(
895 android
.R
.color
.white
));
897 fixRoot((TextView
) v
);
901 private void fixRoot(TextView v
) {
902 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
903 v
.setText(R
.string
.default_display_name_for_root_folder
);
909 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
912 * {@link BroadcastReceiver} to enable syncing feedback in UI
915 public void onReceive(Context context
, Intent intent
) {
916 String event
= intent
.getAction();
917 Log_OC
.d(TAG
, "Received broadcast " + event
);
918 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
919 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
920 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
921 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
925 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
926 mSyncInProgress
= true
;
929 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
930 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
932 if (currentDir
== null
) {
933 // current folder was removed from the server
934 Toast
.makeText( FileDisplayActivity
.this,
935 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
941 if (currentFile
== null
&& !getFile().isFolder()) {
942 // currently selected file was removed in the server, and now we know it
943 cleanSecondFragment();
944 currentFile
= currentDir
;
947 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
948 OCFileListFragment fileListFragment
= getListOfFilesFragment();
949 if (fileListFragment
!= null
) {
950 fileListFragment
.listDirectory(currentDir
);
953 setFile(currentFile
);
956 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
959 if (synchResult != null &&
960 synchResult.isSuccess() &&
961 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
962 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
964 !mRefreshSharesInProgress &&
965 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
972 removeStickyBroadcast(intent
);
973 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
974 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
977 if (synchResult
!= null
) {
978 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
979 mLastSslUntrustedServerResult
= synchResult
;
980 showDialog(DIALOG_SSL_VALIDATOR
);
987 private class UploadFinishReceiver
extends BroadcastReceiver
{
989 * Once the file upload has finished -> update view
990 * @author David A. Velasco
991 * {@link BroadcastReceiver} to enable upload feedback in UI
994 public void onReceive(Context context
, Intent intent
) {
995 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
996 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
997 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
998 OCFile currentDir
= getCurrentDir();
999 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1000 if (sameAccount
&& isDescendant
) {
1001 refeshListOfFilesFragment();
1009 * Class waiting for broadcast events from the {@link FielDownloader} service.
1011 * Updates the UI when a download is started or finished, provided that it is relevant for the
1014 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1016 public void onReceive(Context context
, Intent intent
) {
1017 boolean sameAccount
= isSameAccount(context
, intent
);
1018 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1019 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1021 if (sameAccount
&& isDescendant
) {
1022 refeshListOfFilesFragment();
1023 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1026 removeStickyBroadcast(intent
);
1029 private boolean isDescendant(String downloadedRemotePath
) {
1030 OCFile currentDir
= getCurrentDir();
1031 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1034 private boolean isSameAccount(Context context
, Intent intent
) {
1035 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1036 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1042 * Class waiting for broadcast events from the {@link OperationsService}.
1044 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1045 * operation performed in {@link OperationsService}.
1047 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1048 * probably all the operations associated to the app model.
1050 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1053 public void onReceive(Context context
, Intent intent
) {
1054 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1056 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1057 //mRefreshSharesInProgress = false;
1059 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1060 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1061 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1062 && getStorageManager() != null
1064 refeshListOfFilesFragment();
1066 if ((getSharesResult
!= null
) &&
1067 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1068 mLastSslUntrustedServerResult
= getSharesResult
;
1069 showDialog(DIALOG_SSL_VALIDATOR
);
1072 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1079 public void browseToRoot() {
1080 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1081 if (listOfFiles
!= null
) { // should never be null, indeed
1082 while (mDirectories
.getCount() > 1) {
1085 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1086 listOfFiles
.listDirectory(root
);
1087 setFile(listOfFiles
.getCurrentFile());
1088 startSyncFolderOperation(root
);
1090 cleanSecondFragment();
1094 public void browseTo(OCFile folder
) {
1095 if (folder
== null
|| !folder
.isFolder()) {
1096 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1098 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1099 if (listOfFiles
!= null
) {
1100 setNavigationListWithFolder(folder
);
1101 listOfFiles
.listDirectory(folder
);
1102 setFile(listOfFiles
.getCurrentFile());
1103 startSyncFolderOperation(folder
);
1105 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1107 cleanSecondFragment();
1114 * Updates action bar and second fragment, if in dual pane mode.
1117 public void onBrowsedDownTo(OCFile directory
) {
1118 pushDirname(directory
);
1119 cleanSecondFragment();
1122 startSyncFolderOperation(directory
);
1127 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1129 * @param file Image {@link OCFile} to show.
1132 public void startImagePreview(OCFile file
) {
1133 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1134 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1135 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1136 startActivity(showDetailsIntent
);
1140 * Stars the preview of an already down media {@link OCFile}.
1142 * @param file Media {@link OCFile} to preview.
1143 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1144 * @param autoplay When 'true', the playback will start without user interactions.
1147 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1148 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1149 setSecondFragment(mediaFragment
);
1150 updateFragmentsVisibility(true
);
1151 updateNavigationElementsInActionBar(file
);
1156 * Requests the download of the received {@link OCFile} , updates the UI
1157 * to monitor the download progress and prepares the activity to preview
1158 * or open the file when the download finishes.
1160 * @param file {@link OCFile} to download and preview.
1163 public void startDownloadForPreview(OCFile file
) {
1164 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1165 setSecondFragment(detailFragment
);
1166 mWaitingToPreview
= file
;
1167 requestForDownload();
1168 updateFragmentsVisibility(true
);
1169 updateNavigationElementsInActionBar(file
);
1175 * Shows the information of the {@link OCFile} received as a
1176 * parameter in the second fragment.
1178 * @param file {@link OCFile} whose details will be shown
1181 public void showDetails(OCFile file
) {
1182 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1183 setSecondFragment(detailFragment
);
1184 updateFragmentsVisibility(true
);
1185 updateNavigationElementsInActionBar(file
);
1193 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1194 ActionBar actionBar
= getSupportActionBar();
1195 if (chosenFile
== null
|| mDualPane
) {
1196 // only list of files - set for browsing through folders
1197 OCFile currentDir
= getCurrentDir();
1198 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1199 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1200 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1202 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1204 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1205 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1208 actionBar
.setDisplayHomeAsUpEnabled(true
);
1209 actionBar
.setDisplayShowTitleEnabled(true
);
1210 actionBar
.setTitle(chosenFile
.getFileName());
1211 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1220 public void onFileStateChanged() {
1221 refeshListOfFilesFragment();
1222 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1230 public FileDownloaderBinder
getFileDownloaderBinder() {
1231 return mDownloaderBinder
;
1239 public FileUploaderBinder
getFileUploaderBinder() {
1240 return mUploaderBinder
;
1244 /** Defines callbacks for service binding, passed to bindService() */
1245 private class ListServiceConnection
implements ServiceConnection
{
1248 public void onServiceConnected(ComponentName component
, IBinder service
) {
1249 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1250 Log_OC
.d(TAG
, "Download service connected");
1251 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1252 if (mWaitingToPreview
!= null
) {
1253 requestForDownload();
1256 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1257 Log_OC
.d(TAG
, "Upload service connected");
1258 mUploaderBinder
= (FileUploaderBinder
) service
;
1262 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1263 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1264 if (listOfFiles
!= null
) {
1265 listOfFiles
.listDirectory();
1267 FileFragment secondFragment
= getSecondFragment();
1268 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1269 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1270 detailFragment
.listenForTransferProgress();
1271 detailFragment
.updateFileDetails(false
, false
);
1276 public void onServiceDisconnected(ComponentName component
) {
1277 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1278 Log_OC
.d(TAG
, "Download service disconnected");
1279 mDownloaderBinder
= null
;
1280 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1281 Log_OC
.d(TAG
, "Upload service disconnected");
1282 mUploaderBinder
= null
;
1290 * Launch an intent to request the PIN code to the user before letting him use the app
1292 private void requestPinCode() {
1293 boolean pinStart
= false
;
1294 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1295 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1297 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1298 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1305 public void onSavedCertificate() {
1306 startSyncFolderOperation(getCurrentDir());
1311 public void onFailedSavingCertificate() {
1312 showDialog(DIALOG_CERT_NOT_SAVED
);
1317 * Updates the view associated to the activity after the finish of some operation over files
1318 * in the current account.
1320 * @param operation Removal operation performed.
1321 * @param result Result of the removal.
1324 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1325 super.onRemoteOperationFinish(operation
, result
);
1327 if (operation
instanceof RemoveFileOperation
) {
1328 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1330 } else if (operation
instanceof RenameFileOperation
) {
1331 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1333 } else if (operation
instanceof SynchronizeFileOperation
) {
1334 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1336 } else if (operation
instanceof CreateFolderOperation
) {
1337 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1339 } else if (operation
instanceof CreateShareOperation
) {
1340 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1342 } else if (operation
instanceof UnshareLinkOperation
) {
1343 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1350 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1351 if (result
.isSuccess()) {
1352 refreshShowDetails();
1353 refeshListOfFilesFragment();
1358 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1359 if (result
.isSuccess()) {
1360 refreshShowDetails();
1361 refeshListOfFilesFragment();
1362 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1363 cleanSecondFragment();
1364 refeshListOfFilesFragment();
1368 private void refreshShowDetails() {
1369 FileFragment details
= getSecondFragment();
1370 if (details
!= null
) {
1371 OCFile file
= details
.getFile();
1373 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1374 if (details
instanceof PreviewMediaFragment
) {
1375 // Refresh OCFile of the fragment
1376 ((PreviewMediaFragment
) details
).updateFile(file
);
1381 invalidateOptionsMenu();
1386 * Updates the view associated to the activity after the finish of an operation trying to remove a
1389 * @param operation Removal operation performed.
1390 * @param result Result of the removal.
1392 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1393 dismissLoadingDialog();
1394 if (result
.isSuccess()) {
1395 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1397 OCFile removedFile
= operation
.getFile();
1398 getSecondFragment();
1399 FileFragment second
= getSecondFragment();
1400 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1401 cleanSecondFragment();
1403 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1404 refeshListOfFilesFragment();
1408 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1410 if (result
.isSslRecoverableException()) {
1411 mLastSslUntrustedServerResult
= result
;
1412 showDialog(DIALOG_SSL_VALIDATOR
);
1418 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1420 * @param operation Creation operation performed.
1421 * @param result Result of the creation.
1423 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1424 if (result
.isSuccess()) {
1425 dismissLoadingDialog();
1426 refeshListOfFilesFragment();
1429 dismissLoadingDialog();
1430 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1431 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1434 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1437 } catch (NotFoundException e
) {
1438 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1446 * Updates the view associated to the activity after the finish of an operation trying to rename a
1449 * @param operation Renaming operation performed.
1450 * @param result Result of the renaming.
1452 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1453 dismissLoadingDialog();
1454 OCFile renamedFile
= operation
.getFile();
1455 if (result
.isSuccess()) {
1457 FileFragment details
= getSecondFragment();
1458 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1459 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1462 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1463 refeshListOfFilesFragment();
1467 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1468 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1470 // TODO throw again the new rename dialog
1471 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1472 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1475 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1477 if (result
.isSslRecoverableException()) {
1478 mLastSslUntrustedServerResult
= result
;
1479 showDialog(DIALOG_SSL_VALIDATOR
);
1486 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1487 dismissLoadingDialog();
1488 OCFile syncedFile
= operation
.getLocalFile();
1489 if (!result
.isSuccess()) {
1490 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1491 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1492 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1493 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1499 if (operation
.transferWasRequested()) {
1500 refeshListOfFilesFragment();
1501 onTransferStateChanged(syncedFile
, true
, true
);
1504 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1515 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1517 FileFragment details
= getSecondFragment();
1518 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1519 if (downloading
|| uploading
) {
1520 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1522 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1529 public void onDismiss(EditNameDialog dialog
) {
1530 if (dialog
.getResult()) {
1531 String newDirectoryName
= dialog
.getNewFilename().trim();
1532 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1533 if (newDirectoryName
.length() > 0) {
1534 String path
= getCurrentDir().getRemotePath();
1537 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1538 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1539 operation
.execute( getAccount(),
1540 FileDisplayActivity
.this,
1541 FileDisplayActivity
.this,
1543 FileDisplayActivity
.this);
1545 showLoadingDialog();
1551 private void requestForDownload() {
1552 Account account
= getAccount();
1553 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1554 Intent i
= new Intent(this, FileDownloader
.class);
1555 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1556 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1562 private OCFile
getCurrentDir() {
1563 OCFile file
= getFile();
1565 if (file
.isFolder()) {
1567 } else if (getStorageManager() != null
) {
1568 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1569 return getStorageManager().getFileByPath(parentPath
);
1575 public void startSyncFolderOperation(OCFile folder
) {
1576 long currentSyncTime
= System
.currentTimeMillis();
1578 mSyncInProgress
= true
;
1580 // perform folder synchronization
1581 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1584 getFileOperationsHelper().isSharedSupported(this),
1585 getStorageManager(),
1587 getApplicationContext()
1589 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1591 setSupportProgressBarIndeterminateVisibility(true
);
1595 private void startGetShares() {
1596 // Get shared files/folders
1597 Intent intent = new Intent(this, OperationsService.class);
1598 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1599 startService(intent);
1601 mRefreshSharesInProgress = true;