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
.Configuration
;
38 import android
.content
.res
.Resources
.NotFoundException
;
39 import android
.database
.Cursor
;
40 import android
.net
.Uri
;
41 import android
.os
.Bundle
;
42 import android
.os
.IBinder
;
43 import android
.preference
.PreferenceManager
;
44 import android
.provider
.MediaStore
;
45 import android
.support
.v4
.app
.Fragment
;
46 import android
.support
.v4
.app
.FragmentTransaction
;
47 //import android.support.v4.content.LocalBroadcastManager;
48 import android
.util
.Log
;
49 import android
.view
.View
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ArrayAdapter
;
52 import android
.widget
.TextView
;
53 import android
.widget
.Toast
;
55 import com
.actionbarsherlock
.app
.ActionBar
;
56 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
57 import com
.actionbarsherlock
.view
.Menu
;
58 import com
.actionbarsherlock
.view
.MenuInflater
;
59 import com
.actionbarsherlock
.view
.MenuItem
;
60 import com
.actionbarsherlock
.view
.Window
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileObserverService
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
74 import com
.owncloud
.android
.operations
.CreateShareOperation
;
75 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
76 import com
.owncloud
.android
.operations
.RenameFileOperation
;
77 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
78 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
79 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
80 import com
.owncloud
.android
.services
.OperationsService
;
81 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
82 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
83 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
84 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
86 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
87 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
88 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
89 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
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";
124 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
126 public static final int DIALOG_SHORT_WAIT
= 0;
127 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
128 private static final int DIALOG_SSL_VALIDATOR
= 2;
129 private static final int DIALOG_CERT_NOT_SAVED
= 3;
131 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
133 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
134 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
136 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
138 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
139 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
141 private OCFile mWaitingToPreview
;
143 private boolean mSyncInProgress
= false
;
144 //private boolean mRefreshSharesInProgress = false;
146 private OCFile mWaitingToSend
;
149 protected void onCreate(Bundle savedInstanceState
) {
150 Log_OC
.d(TAG
, "onCreate() start");
151 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
153 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
155 /// bindings to transference services
156 mUploadConnection
= new ListServiceConnection();
157 mDownloadConnection
= new ListServiceConnection();
158 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
159 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
161 // PIN CODE request ; best location is to decide, let's try this first
162 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
164 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
169 Intent observer_intent
= new Intent(this, FileObserverService
.class);
170 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
171 startService(observer_intent
);
173 /// Load of saved instance state
174 if(savedInstanceState
!= null
) {
175 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
178 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
181 mWaitingToPreview
= null
;
182 mSyncInProgress
= false
;
183 //mRefreshSharesInProgress = false;
184 mWaitingToSend
= null
;
189 // Inflate and set the layout view
190 setContentView(R
.layout
.files
);
191 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
192 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
193 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
194 if (savedInstanceState
== null
) {
195 createMinFragments();
197 Log_OC
.d(TAG
, "Init the secondFragment again");
199 initFragmentsWithFile();
204 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
205 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
206 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
208 Log_OC
.d(TAG
, "onCreate() end");
212 protected void onStart() {
214 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 refeshListOfFilesFragment();
219 protected void onDestroy() {
221 if (mDownloadConnection
!= null
)
222 unbindService(mDownloadConnection
);
223 if (mUploadConnection
!= null
)
224 unbindService(mUploadConnection
);
228 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
231 protected void onAccountSet(boolean stateWasRecovered
) {
232 super.onAccountSet(stateWasRecovered
);
233 if (getAccount() != null
) {
234 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
235 OCFile file
= getFile();
236 // get parent from path
237 String parentPath
= "";
239 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
240 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
241 // get parent from path
242 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
243 if (getStorageManager().getFileByPath(parentPath
) == null
)
244 file
= null
; // not able to know the directory where the file is uploading
246 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
250 // fall back to root folder
251 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
254 setNavigationListWithFolder(file
);
256 if (!stateWasRecovered
) {
257 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
258 initFragmentsWithFile();
259 if (file
.isFolder()) {
260 startSyncFolderOperation(file
);
264 updateFragmentsVisibility(!file
.isFolder());
265 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
271 private void setNavigationListWithFolder(OCFile file
) {
272 mDirectories
.clear();
273 OCFile fileIt
= file
;
275 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
276 if (fileIt
.isFolder()) {
277 mDirectories
.add(fileIt
.getFileName());
279 // get parent from path
280 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
281 fileIt
= getStorageManager().getFileByPath(parentPath
);
283 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
287 private void createMinFragments() {
288 OCFileListFragment listOfFiles
= new OCFileListFragment();
289 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
290 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
291 transaction
.commit();
294 private void initFragmentsWithFile() {
295 if (getAccount() != null
&& getFile() != null
) {
297 OCFileListFragment listOfFiles
= getListOfFilesFragment();
298 if (listOfFiles
!= null
) {
299 listOfFiles
.listDirectory(getCurrentDir());
301 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
305 OCFile file
= getFile();
306 Fragment secondFragment
= chooseInitialSecondFragment(file
);
307 if (secondFragment
!= null
) {
308 setSecondFragment(secondFragment
);
309 updateFragmentsVisibility(true
);
310 updateNavigationElementsInActionBar(file
);
313 cleanSecondFragment();
317 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
318 if (getAccount() == null
) {
319 Log
.wtf(TAG
, "\t account is NULL");
321 if (getFile() == null
) {
322 Log
.wtf(TAG
, "\t file is NULL");
327 private Fragment
chooseInitialSecondFragment(OCFile file
) {
328 Fragment secondFragment
= null
;
329 if (file
!= null
&& !file
.isFolder()) {
330 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
331 && file
.getLastSyncDateForProperties() > 0 // temporal fix
333 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
334 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
335 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
338 secondFragment
= new FileDetailFragment(file
, getAccount());
341 return secondFragment
;
346 * Replaces the second fragment managed by the activity with the received as
349 * Assumes never will be more than two fragments managed at the same time.
351 * @param fragment New second Fragment to set.
353 private void setSecondFragment(Fragment fragment
) {
354 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
355 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
356 transaction
.commit();
360 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
362 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
363 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
365 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
369 } else if (existsSecondFragment
) {
370 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
371 mLeftFragmentContainer
.setVisibility(View
.GONE
);
373 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
378 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
381 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
382 mRightFragmentContainer
.setVisibility(View
.GONE
);
388 private OCFileListFragment
getListOfFilesFragment() {
389 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
390 if (listOfFiles
!= null
) {
391 return (OCFileListFragment
)listOfFiles
;
393 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
397 protected FileFragment
getSecondFragment() {
398 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
399 if (second
!= null
) {
400 return (FileFragment
)second
;
405 public void cleanSecondFragment() {
406 Fragment second
= getSecondFragment();
407 if (second
!= null
) {
408 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
412 updateFragmentsVisibility(false
);
413 updateNavigationElementsInActionBar(null
);
416 protected void refeshListOfFilesFragment() {
417 OCFileListFragment fileListFragment
= getListOfFilesFragment();
418 if (fileListFragment
!= null
) {
419 fileListFragment
.listDirectory();
423 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
424 FileFragment secondFragment
= getSecondFragment();
425 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
426 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
427 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
428 OCFile fileInFragment
= detailsFragment
.getFile();
429 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
430 // the user browsed to other file ; forget the automatic preview
431 mWaitingToPreview
= null
;
433 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
434 // grant that the right panel updates the progress bar
435 detailsFragment
.listenForTransferProgress();
436 detailsFragment
.updateFileDetails(true
, false
);
438 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
439 // update the right panel
440 boolean detailsFragmentChanged
= false
;
443 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
444 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
445 startMediaPreview(mWaitingToPreview
, 0, true
);
446 detailsFragmentChanged
= true
;
448 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
451 mWaitingToPreview
= null
;
453 if (!detailsFragmentChanged
) {
454 detailsFragment
.updateFileDetails(false
, (success
));
461 public boolean onCreateOptionsMenu(Menu menu
) {
462 MenuInflater inflater
= getSherlock().getMenuInflater();
463 inflater
.inflate(R
.menu
.main_menu
, menu
);
468 public boolean onOptionsItemSelected(MenuItem item
) {
469 boolean retval
= true
;
470 switch (item
.getItemId()) {
471 case R
.id
.action_create_dir
: {
472 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
473 dialog
.show(getSupportFragmentManager(), "createdirdialog");
476 case R
.id
.action_sync_account
: {
477 startSynchronization();
480 case R
.id
.action_upload
: {
481 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
484 case R
.id
.action_settings
: {
485 Intent settingsIntent
= new Intent(this, Preferences
.class);
486 startActivity(settingsIntent
);
489 case android
.R
.id
.home
: {
490 FileFragment second
= getSecondFragment();
491 OCFile currentDir
= getCurrentDir();
492 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
493 (second
!= null
&& second
.getFile() != null
)) {
500 retval
= super.onOptionsItemSelected(item
);
505 private void startSynchronization() {
506 Log_OC
.e(TAG
, "Got to start sync");
507 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
508 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
509 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
510 Bundle bundle
= new Bundle();
511 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
512 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
513 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
514 ContentResolver
.requestSync(
516 MainApp
.getAuthority(), bundle
);
518 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
519 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
520 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
521 builder
.setExpedited(true
);
522 builder
.setManual(true
);
524 SyncRequest request
= builder
.build();
525 ContentResolver
.requestSync(request
);
531 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
532 if (itemPosition
!= 0) {
533 String targetPath
= "";
534 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
535 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
537 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
538 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
539 if (targetFolder
!= null
) {
540 browseTo(targetFolder
);
543 // the next operation triggers a new call to this method, but it's necessary to
544 // ensure that the name exposed in the action bar is the current directory when the
545 // user selected it in the navigation list
546 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
547 getSupportActionBar().setSelectedNavigationItem(0);
553 * Called, when the user selected something for uploading
555 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
556 super.onActivityResult(requestCode
, resultCode
, data
);
558 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
559 requestSimpleUpload(data
, resultCode
);
561 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
562 requestMultipleUpload(data
, resultCode
);
567 private void requestMultipleUpload(Intent data
, int resultCode
) {
568 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
569 if (filePaths
!= null
) {
570 String
[] remotePaths
= new String
[filePaths
.length
];
571 String remotePathBase
= "";
572 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
573 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
575 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
576 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
577 for (int j
= 0; j
< remotePaths
.length
; j
++) {
578 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
581 Intent i
= new Intent(this, FileUploader
.class);
582 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
583 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
584 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
585 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
586 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
587 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
591 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
592 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
599 private void requestSimpleUpload(Intent data
, int resultCode
) {
600 String filepath
= null
;
602 Uri selectedImageUri
= data
.getData();
604 String filemanagerstring
= selectedImageUri
.getPath();
605 String selectedImagePath
= getPath(selectedImageUri
);
607 if (selectedImagePath
!= null
)
608 filepath
= selectedImagePath
;
610 filepath
= filemanagerstring
;
612 } catch (Exception e
) {
613 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
617 if (filepath
== null
) {
618 Log_OC
.e(TAG
, "Couldnt resolve path to file");
619 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
625 Intent i
= new Intent(this, FileUploader
.class);
626 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
628 String remotepath
= new String();
629 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
630 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
632 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
633 remotepath
+= OCFile
.PATH_SEPARATOR
;
634 remotepath
+= new File(filepath
).getName();
636 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
637 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
638 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
639 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
640 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
645 public void onBackPressed() {
646 OCFileListFragment listOfFiles
= getListOfFilesFragment();
647 if (mDualPane
|| getSecondFragment() == null
) {
648 if (listOfFiles
!= null
) { // should never be null, indeed
649 if (mDirectories
.getCount() <= 1) {
653 int levelsUp
= listOfFiles
.onBrowseUp();
654 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
659 if (listOfFiles
!= null
) { // should never be null, indeed
660 setFile(listOfFiles
.getCurrentFile());
662 cleanSecondFragment();
667 protected void onSaveInstanceState(Bundle outState
) {
668 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
669 Log_OC
.e(TAG
, "onSaveInstanceState() start");
670 super.onSaveInstanceState(outState
);
671 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
672 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
673 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
674 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
676 Log_OC
.d(TAG
, "onSaveInstanceState() end");
682 protected void onResume() {
684 Log_OC
.e(TAG
, "onResume() start");
686 // Listen for sync messages
687 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
688 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
689 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
690 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
691 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
692 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
693 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
694 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
695 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
697 // Listen for upload messages
698 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
699 mUploadFinishReceiver
= new UploadFinishReceiver();
700 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
702 // Listen for download messages
703 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
704 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
705 mDownloadFinishReceiver
= new DownloadFinishReceiver();
706 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
708 // Listen for messages from the OperationsService
710 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
711 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
712 mOperationsServiceReceiver = new OperationsServiceReceiver();
713 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
716 Log_OC
.d(TAG
, "onResume() end");
721 protected void onPause() {
723 Log_OC
.e(TAG
, "onPause() start");
724 if (mSyncBroadcastReceiver
!= null
) {
725 unregisterReceiver(mSyncBroadcastReceiver
);
726 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
727 mSyncBroadcastReceiver
= null
;
729 if (mUploadFinishReceiver
!= null
) {
730 unregisterReceiver(mUploadFinishReceiver
);
731 mUploadFinishReceiver
= null
;
733 if (mDownloadFinishReceiver
!= null
) {
734 unregisterReceiver(mDownloadFinishReceiver
);
735 mDownloadFinishReceiver
= null
;
738 if (mOperationsServiceReceiver != null) {
739 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
740 mOperationsServiceReceiver = null;
743 Log_OC
.d(TAG
, "onPause() end");
748 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
749 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
750 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
756 protected Dialog
onCreateDialog(int id
) {
757 Dialog dialog
= null
;
758 AlertDialog
.Builder builder
;
760 case DIALOG_SHORT_WAIT
: {
761 ProgressDialog working_dialog
= new ProgressDialog(this);
762 working_dialog
.setMessage(getResources().getString(
763 R
.string
.wait_a_moment
));
764 working_dialog
.setIndeterminate(true
);
765 working_dialog
.setCancelable(false
);
766 dialog
= working_dialog
;
769 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
771 String
[] items
= null
;
773 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
774 getString(R
.string
.actionbar_upload_from_apps
),
775 getString(R
.string
.actionbar_failed_instant_upload
) };
777 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
778 getString(R
.string
.actionbar_upload_from_apps
) };
780 if (InstantUploadActivity
.IS_ENABLED
)
785 builder
= new AlertDialog
.Builder(this);
786 builder
.setTitle(R
.string
.actionbar_upload
);
787 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
788 public void onClick(DialogInterface dialog
, int item
) {
791 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
792 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
793 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
795 // TODO create and handle new fragment
796 // LocalFileListFragment
798 } else if (item
== 1) {
799 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
800 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
801 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
802 ACTION_SELECT_CONTENT_FROM_APPS
);
803 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
804 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
805 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
806 startActivity(action
);
810 dialog
= builder
.create();
813 case DIALOG_SSL_VALIDATOR
: {
814 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
817 case DIALOG_CERT_NOT_SAVED
: {
818 builder
= new AlertDialog
.Builder(this);
819 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
820 builder
.setCancelable(false
);
821 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
823 public void onClick(DialogInterface dialog
, int which
) {
827 dialog
= builder
.create();
839 * Translates a content URI of an image to a physical path
841 * @param uri The URI to resolve
842 * @return The path to the image or null if it could not be found
844 public String
getPath(Uri uri
) {
845 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
846 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
847 if (cursor
!= null
) {
848 int column_index
= cursor
849 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
850 cursor
.moveToFirst();
851 return cursor
.getString(column_index
);
857 * Pushes a directory to the drop down list
858 * @param directory to push
859 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
861 public void pushDirname(OCFile directory
) {
862 if(!directory
.isFolder()){
863 throw new IllegalArgumentException("Only directories may be pushed!");
865 mDirectories
.insert(directory
.getFileName(), 0);
870 * Pops a directory name from the drop down list
871 * @return True, unless the stack is empty
873 public boolean popDirname() {
874 mDirectories
.remove(mDirectories
.getItem(0));
875 return !mDirectories
.isEmpty();
878 // Custom array adapter to override text colors
879 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
881 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
885 public View
getView(int position
, View convertView
, ViewGroup parent
) {
886 View v
= super.getView(position
, convertView
, parent
);
888 ((TextView
) v
).setTextColor(getResources().getColorStateList(
889 android
.R
.color
.white
));
891 fixRoot((TextView
) v
);
895 public View
getDropDownView(int position
, View convertView
,
897 View v
= super.getDropDownView(position
, convertView
, parent
);
899 ((TextView
) v
).setTextColor(getResources().getColorStateList(
900 android
.R
.color
.white
));
902 fixRoot((TextView
) v
);
906 private void fixRoot(TextView v
) {
907 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
908 v
.setText(R
.string
.default_display_name_for_root_folder
);
914 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
917 * {@link BroadcastReceiver} to enable syncing feedback in UI
920 public void onReceive(Context context
, Intent intent
) {
921 String event
= intent
.getAction();
922 Log_OC
.d(TAG
, "Received broadcast " + event
);
923 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
924 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
925 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
926 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
930 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
931 mSyncInProgress
= true
;
934 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
935 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
937 if (currentDir
== null
) {
938 // current folder was removed from the server
939 Toast
.makeText( FileDisplayActivity
.this,
940 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
946 if (currentFile
== null
&& !getFile().isFolder()) {
947 // currently selected file was removed in the server, and now we know it
948 cleanSecondFragment();
949 currentFile
= currentDir
;
952 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
953 OCFileListFragment fileListFragment
= getListOfFilesFragment();
954 if (fileListFragment
!= null
) {
955 fileListFragment
.listDirectory(currentDir
);
958 setFile(currentFile
);
961 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
964 if (synchResult != null &&
965 synchResult.isSuccess() &&
966 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
967 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
969 !mRefreshSharesInProgress &&
970 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
977 removeStickyBroadcast(intent
);
978 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
979 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
982 if (synchResult
!= null
) {
983 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
984 mLastSslUntrustedServerResult
= synchResult
;
985 showDialog(DIALOG_SSL_VALIDATOR
);
992 private class UploadFinishReceiver
extends BroadcastReceiver
{
994 * Once the file upload has finished -> update view
995 * @author David A. Velasco
996 * {@link BroadcastReceiver} to enable upload feedback in UI
999 public void onReceive(Context context
, Intent intent
) {
1000 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1001 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1002 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1003 OCFile currentDir
= getCurrentDir();
1004 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1005 if (sameAccount
&& isDescendant
) {
1006 refeshListOfFilesFragment();
1014 * Class waiting for broadcast events from the {@link FielDownloader} service.
1016 * Updates the UI when a download is started or finished, provided that it is relevant for the
1019 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1021 public void onReceive(Context context
, Intent intent
) {
1022 boolean sameAccount
= isSameAccount(context
, intent
);
1023 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1024 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1026 if (sameAccount
&& isDescendant
) {
1027 refeshListOfFilesFragment();
1028 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1031 if (mWaitingToSend
!= null
) {
1032 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1033 if (mWaitingToSend
.isDown()) {
1034 sendDownloadedFile();
1038 removeStickyBroadcast(intent
);
1041 private boolean isDescendant(String downloadedRemotePath
) {
1042 OCFile currentDir
= getCurrentDir();
1043 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1046 private boolean isSameAccount(Context context
, Intent intent
) {
1047 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1048 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1054 * Class waiting for broadcast events from the {@link OperationsService}.
1056 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1057 * operation performed in {@link OperationsService}.
1059 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1060 * probably all the operations associated to the app model.
1062 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1065 public void onReceive(Context context
, Intent intent
) {
1066 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1068 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1069 //mRefreshSharesInProgress = false;
1071 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1072 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1073 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1074 && getStorageManager() != null
1076 refeshListOfFilesFragment();
1078 if ((getSharesResult
!= null
) &&
1079 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1080 mLastSslUntrustedServerResult
= getSharesResult
;
1081 showDialog(DIALOG_SSL_VALIDATOR
);
1084 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1091 public void browseToRoot() {
1092 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1093 if (listOfFiles
!= null
) { // should never be null, indeed
1094 while (mDirectories
.getCount() > 1) {
1097 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1098 listOfFiles
.listDirectory(root
);
1099 setFile(listOfFiles
.getCurrentFile());
1100 startSyncFolderOperation(root
);
1102 cleanSecondFragment();
1106 public void browseTo(OCFile folder
) {
1107 if (folder
== null
|| !folder
.isFolder()) {
1108 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1110 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1111 if (listOfFiles
!= null
) {
1112 setNavigationListWithFolder(folder
);
1113 listOfFiles
.listDirectory(folder
);
1114 setFile(listOfFiles
.getCurrentFile());
1115 startSyncFolderOperation(folder
);
1117 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1119 cleanSecondFragment();
1126 * Updates action bar and second fragment, if in dual pane mode.
1129 public void onBrowsedDownTo(OCFile directory
) {
1130 pushDirname(directory
);
1131 cleanSecondFragment();
1134 startSyncFolderOperation(directory
);
1139 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1141 * @param file Image {@link OCFile} to show.
1144 public void startImagePreview(OCFile file
) {
1145 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1146 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1147 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1148 startActivity(showDetailsIntent
);
1152 * Stars the preview of an already down media {@link OCFile}.
1154 * @param file Media {@link OCFile} to preview.
1155 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1156 * @param autoplay When 'true', the playback will start without user interactions.
1159 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1160 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1161 setSecondFragment(mediaFragment
);
1162 updateFragmentsVisibility(true
);
1163 updateNavigationElementsInActionBar(file
);
1168 * Requests the download of the received {@link OCFile} , updates the UI
1169 * to monitor the download progress and prepares the activity to preview
1170 * or open the file when the download finishes.
1172 * @param file {@link OCFile} to download and preview.
1175 public void startDownloadForPreview(OCFile file
) {
1176 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1177 setSecondFragment(detailFragment
);
1178 mWaitingToPreview
= file
;
1179 requestForDownload();
1180 updateFragmentsVisibility(true
);
1181 updateNavigationElementsInActionBar(file
);
1187 * Shows the information of the {@link OCFile} received as a
1188 * parameter in the second fragment.
1190 * @param file {@link OCFile} whose details will be shown
1193 public void showDetails(OCFile file
) {
1194 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1195 setSecondFragment(detailFragment
);
1196 updateFragmentsVisibility(true
);
1197 updateNavigationElementsInActionBar(file
);
1205 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1206 ActionBar actionBar
= getSupportActionBar();
1207 if (chosenFile
== null
|| mDualPane
) {
1208 // only list of files - set for browsing through folders
1209 OCFile currentDir
= getCurrentDir();
1210 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1211 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1212 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1214 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1216 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1217 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1220 actionBar
.setDisplayHomeAsUpEnabled(true
);
1221 actionBar
.setDisplayShowTitleEnabled(true
);
1222 actionBar
.setTitle(chosenFile
.getFileName());
1223 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1232 public void onFileStateChanged() {
1233 refeshListOfFilesFragment();
1234 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1242 public FileDownloaderBinder
getFileDownloaderBinder() {
1243 return mDownloaderBinder
;
1251 public FileUploaderBinder
getFileUploaderBinder() {
1252 return mUploaderBinder
;
1256 /** Defines callbacks for service binding, passed to bindService() */
1257 private class ListServiceConnection
implements ServiceConnection
{
1260 public void onServiceConnected(ComponentName component
, IBinder service
) {
1261 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1262 Log_OC
.d(TAG
, "Download service connected");
1263 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1264 if (mWaitingToPreview
!= null
) {
1265 requestForDownload();
1268 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1269 Log_OC
.d(TAG
, "Upload service connected");
1270 mUploaderBinder
= (FileUploaderBinder
) service
;
1274 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1275 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1276 if (listOfFiles
!= null
) {
1277 listOfFiles
.listDirectory();
1279 FileFragment secondFragment
= getSecondFragment();
1280 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1281 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1282 detailFragment
.listenForTransferProgress();
1283 detailFragment
.updateFileDetails(false
, false
);
1288 public void onServiceDisconnected(ComponentName component
) {
1289 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1290 Log_OC
.d(TAG
, "Download service disconnected");
1291 mDownloaderBinder
= null
;
1292 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1293 Log_OC
.d(TAG
, "Upload service disconnected");
1294 mUploaderBinder
= null
;
1302 * Launch an intent to request the PIN code to the user before letting him use the app
1304 private void requestPinCode() {
1305 boolean pinStart
= false
;
1306 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1307 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1309 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1310 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1317 public void onSavedCertificate() {
1318 startSyncFolderOperation(getCurrentDir());
1323 public void onFailedSavingCertificate() {
1324 showDialog(DIALOG_CERT_NOT_SAVED
);
1329 * Updates the view associated to the activity after the finish of some operation over files
1330 * in the current account.
1332 * @param operation Removal operation performed.
1333 * @param result Result of the removal.
1336 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1337 super.onRemoteOperationFinish(operation
, result
);
1339 if (operation
instanceof RemoveFileOperation
) {
1340 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1342 } else if (operation
instanceof RenameFileOperation
) {
1343 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1345 } else if (operation
instanceof SynchronizeFileOperation
) {
1346 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1348 } else if (operation
instanceof CreateFolderOperation
) {
1349 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1351 } else if (operation
instanceof CreateShareOperation
) {
1352 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1354 } else if (operation
instanceof UnshareLinkOperation
) {
1355 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1362 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1363 if (result
.isSuccess()) {
1364 refreshShowDetails();
1365 refeshListOfFilesFragment();
1370 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1371 if (result
.isSuccess()) {
1372 refreshShowDetails();
1373 refeshListOfFilesFragment();
1374 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1375 cleanSecondFragment();
1376 refeshListOfFilesFragment();
1380 private void refreshShowDetails() {
1381 FileFragment details
= getSecondFragment();
1382 if (details
!= null
) {
1383 OCFile file
= details
.getFile();
1385 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1386 if (details
instanceof PreviewMediaFragment
) {
1387 // Refresh OCFile of the fragment
1388 ((PreviewMediaFragment
) details
).updateFile(file
);
1393 invalidateOptionsMenu();
1398 * Updates the view associated to the activity after the finish of an operation trying to remove a
1401 * @param operation Removal operation performed.
1402 * @param result Result of the removal.
1404 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1405 dismissLoadingDialog();
1406 if (result
.isSuccess()) {
1407 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1409 OCFile removedFile
= operation
.getFile();
1410 getSecondFragment();
1411 FileFragment second
= getSecondFragment();
1412 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1413 cleanSecondFragment();
1415 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1416 refeshListOfFilesFragment();
1420 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1422 if (result
.isSslRecoverableException()) {
1423 mLastSslUntrustedServerResult
= result
;
1424 showDialog(DIALOG_SSL_VALIDATOR
);
1430 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1432 * @param operation Creation operation performed.
1433 * @param result Result of the creation.
1435 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1436 if (result
.isSuccess()) {
1437 dismissLoadingDialog();
1438 refeshListOfFilesFragment();
1441 dismissLoadingDialog();
1442 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1443 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1446 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1449 } catch (NotFoundException e
) {
1450 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1458 * Updates the view associated to the activity after the finish of an operation trying to rename a
1461 * @param operation Renaming operation performed.
1462 * @param result Result of the renaming.
1464 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1465 dismissLoadingDialog();
1466 OCFile renamedFile
= operation
.getFile();
1467 if (result
.isSuccess()) {
1469 FileFragment details
= getSecondFragment();
1470 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1471 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1474 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1475 refeshListOfFilesFragment();
1479 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1480 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1482 // TODO throw again the new rename dialog
1483 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1484 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1487 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1489 if (result
.isSslRecoverableException()) {
1490 mLastSslUntrustedServerResult
= result
;
1491 showDialog(DIALOG_SSL_VALIDATOR
);
1498 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1499 dismissLoadingDialog();
1500 OCFile syncedFile
= operation
.getLocalFile();
1501 if (!result
.isSuccess()) {
1502 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1503 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1504 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1505 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1511 if (operation
.transferWasRequested()) {
1512 refeshListOfFilesFragment();
1513 onTransferStateChanged(syncedFile
, true
, true
);
1516 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1527 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1529 FileFragment details
= getSecondFragment();
1530 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1531 if (downloading
|| uploading
) {
1532 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1534 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1541 public void onDismiss(EditNameDialog dialog
) {
1542 if (dialog
.getResult()) {
1543 String newDirectoryName
= dialog
.getNewFilename().trim();
1544 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1545 if (newDirectoryName
.length() > 0) {
1546 String path
= getCurrentDir().getRemotePath();
1549 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1550 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1551 operation
.execute( getAccount(),
1552 FileDisplayActivity
.this,
1553 FileDisplayActivity
.this,
1555 FileDisplayActivity
.this);
1557 showLoadingDialog();
1563 private void requestForDownload() {
1564 Account account
= getAccount();
1565 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1566 Intent i
= new Intent(this, FileDownloader
.class);
1567 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1568 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1574 private OCFile
getCurrentDir() {
1575 OCFile file
= getFile();
1577 if (file
.isFolder()) {
1579 } else if (getStorageManager() != null
) {
1580 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1581 return getStorageManager().getFileByPath(parentPath
);
1587 public void startSyncFolderOperation(OCFile folder
) {
1588 long currentSyncTime
= System
.currentTimeMillis();
1590 mSyncInProgress
= true
;
1592 // perform folder synchronization
1593 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1596 getFileOperationsHelper().isSharedSupported(this),
1597 getStorageManager(),
1599 getApplicationContext()
1601 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1603 setSupportProgressBarIndeterminateVisibility(true
);
1607 private void startGetShares() {
1608 // Get shared files/folders
1609 Intent intent = new Intent(this, OperationsService.class);
1610 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1611 startService(intent);
1613 mRefreshSharesInProgress = true;
1618 * Requests the download of the received {@link OCFile} , updates the UI
1619 * to monitor the download progress and prepares the activity to send the file
1620 * when the download finishes.
1622 * @param file {@link OCFile} to download and preview.
1625 public void startDownloadForSending(OCFile file
) {
1626 mWaitingToSend
= file
;
1627 requestForDownload(mWaitingToSend
);
1628 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1629 updateFragmentsVisibility(hasSecondFragment
);
1632 private void requestForDownload(OCFile file
) {
1633 Account account
= getAccount();
1634 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1635 Intent i
= new Intent(this, FileDownloader
.class);
1636 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1637 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1642 private void sendDownloadedFile(){
1643 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
, this);
1644 mWaitingToSend
= null
;