1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.Dialog
;
26 import android
.app
.ProgressDialog
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.ComponentName
;
29 import android
.content
.ContentResolver
;
30 import android
.content
.Context
;
31 import android
.content
.DialogInterface
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.content
.SyncRequest
;
37 import android
.content
.res
.Resources
.NotFoundException
;
38 import android
.database
.Cursor
;
39 import android
.net
.Uri
;
40 import android
.os
.Bundle
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.provider
.MediaStore
;
44 import android
.support
.v4
.app
.Fragment
;
45 import android
.support
.v4
.app
.FragmentManager
;
46 import android
.support
.v4
.app
.FragmentTransaction
;
47 //import android.support.v4.content.LocalBroadcastManager;
48 import android
.util
.Log
;
49 import android
.view
.View
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ArrayAdapter
;
52 import android
.widget
.TextView
;
53 import android
.widget
.Toast
;
55 import com
.actionbarsherlock
.app
.ActionBar
;
56 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
57 import com
.actionbarsherlock
.view
.Menu
;
58 import com
.actionbarsherlock
.view
.MenuInflater
;
59 import com
.actionbarsherlock
.view
.MenuItem
;
60 import com
.actionbarsherlock
.view
.Window
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileObserverService
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
71 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
75 import com
.owncloud
.android
.operations
.CreateShareOperation
;
76 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
77 import com
.owncloud
.android
.operations
.RenameFileOperation
;
78 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
79 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
80 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
81 import com
.owncloud
.android
.services
.OperationsService
;
82 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
83 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
86 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
87 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
88 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
89 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
92 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
93 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
94 import com
.owncloud
.android
.utils
.DisplayUtils
;
95 import com
.owncloud
.android
.utils
.Log_OC
;
99 * Displays, what files the user has available in his ownCloud.
101 * @author Bartek Przybylski
102 * @author David A. Velasco
105 public class FileDisplayActivity
extends HookActivity
implements
106 FileFragment
.ContainerActivity
, OnNavigationListener
,
107 OnSslUntrustedCertListener
, EditNameDialogListener
{
109 private ArrayAdapter
<String
> mDirectories
;
111 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
112 private UploadFinishReceiver mUploadFinishReceiver
;
113 private DownloadFinishReceiver mDownloadFinishReceiver
;
114 //private OperationsServiceReceiver mOperationsServiceReceiver;
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
= 2;
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 String DIALOG_UNTRUSTED_CERT
;
148 private OCFile mWaitingToSend
;
151 protected void onCreate(Bundle savedInstanceState
) {
152 Log_OC
.d(TAG
, "onCreate() start");
153 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
155 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
157 // PIN CODE request ; best location is to decide, let's try this first
158 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
160 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
165 Intent observer_intent
= new Intent(this, FileObserverService
.class);
166 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
167 startService(observer_intent
);
169 /// Load of saved instance state
170 if(savedInstanceState
!= null
) {
171 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
172 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
173 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
174 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
177 mWaitingToPreview
= null
;
178 mSyncInProgress
= false
;
179 //mRefreshSharesInProgress = false;
180 mWaitingToSend
= null
;
185 // Inflate and set the layout view
186 setContentView(R
.layout
.files
);
187 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
188 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
189 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
190 if (savedInstanceState
== null
) {
191 createMinFragments();
193 Log_OC
.d(TAG
, "Init the secondFragment again");
195 initFragmentsWithFile();
200 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
201 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
202 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
204 Log_OC
.d(TAG
, "onCreate() end");
208 protected void onStart() {
210 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
212 refeshListOfFilesFragment();
217 protected void onDestroy() {
222 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
225 protected void onAccountSet(boolean stateWasRecovered
) {
226 super.onAccountSet(stateWasRecovered
);
227 if (getAccount() != null
) {
228 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
229 OCFile file
= getFile();
230 // get parent from path
231 String parentPath
= "";
233 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
234 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
235 // get parent from path
236 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
237 if (getStorageManager().getFileByPath(parentPath
) == null
)
238 file
= null
; // not able to know the directory where the file is uploading
240 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
244 // fall back to root folder
245 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
248 setNavigationListWithFolder(file
);
250 if (!stateWasRecovered
) {
251 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
252 initFragmentsWithFile();
253 if (file
.isFolder()) {
254 startSyncFolderOperation(file
);
258 updateFragmentsVisibility(!file
.isFolder());
259 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
265 private void setNavigationListWithFolder(OCFile file
) {
266 mDirectories
.clear();
267 OCFile fileIt
= file
;
269 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
270 if (fileIt
.isFolder()) {
271 mDirectories
.add(fileIt
.getFileName());
273 // get parent from path
274 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
275 fileIt
= getStorageManager().getFileByPath(parentPath
);
277 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
281 private void createMinFragments() {
282 OCFileListFragment listOfFiles
= new OCFileListFragment();
283 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
284 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
285 transaction
.commit();
288 private void initFragmentsWithFile() {
289 if (getAccount() != null
&& getFile() != null
) {
291 OCFileListFragment listOfFiles
= getListOfFilesFragment();
292 if (listOfFiles
!= null
) {
293 listOfFiles
.listDirectory(getCurrentDir());
295 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
299 OCFile file
= getFile();
300 Fragment secondFragment
= chooseInitialSecondFragment(file
);
301 if (secondFragment
!= null
) {
302 setSecondFragment(secondFragment
);
303 updateFragmentsVisibility(true
);
304 updateNavigationElementsInActionBar(file
);
307 cleanSecondFragment();
311 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
312 if (getAccount() == null
) {
313 Log
.wtf(TAG
, "\t account is NULL");
315 if (getFile() == null
) {
316 Log
.wtf(TAG
, "\t file is NULL");
321 private Fragment
chooseInitialSecondFragment(OCFile file
) {
322 Fragment secondFragment
= null
;
323 if (file
!= null
&& !file
.isFolder()) {
324 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
325 && file
.getLastSyncDateForProperties() > 0 // temporal fix
327 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
328 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
329 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
332 secondFragment
= new FileDetailFragment(file
, getAccount());
335 return secondFragment
;
340 * Replaces the second fragment managed by the activity with the received as
343 * Assumes never will be more than two fragments managed at the same time.
345 * @param fragment New second Fragment to set.
347 private void setSecondFragment(Fragment fragment
) {
348 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
349 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
350 transaction
.commit();
354 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
356 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
357 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
359 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
360 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
363 } else if (existsSecondFragment
) {
364 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
365 mLeftFragmentContainer
.setVisibility(View
.GONE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
372 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
373 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
376 mRightFragmentContainer
.setVisibility(View
.GONE
);
382 private OCFileListFragment
getListOfFilesFragment() {
383 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
384 if (listOfFiles
!= null
) {
385 return (OCFileListFragment
)listOfFiles
;
387 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
391 protected FileFragment
getSecondFragment() {
392 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
393 if (second
!= null
) {
394 return (FileFragment
)second
;
399 public void cleanSecondFragment() {
400 Fragment second
= getSecondFragment();
401 if (second
!= null
) {
402 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
406 updateFragmentsVisibility(false
);
407 updateNavigationElementsInActionBar(null
);
411 protected void refeshListOfFilesFragment() {
412 OCFileListFragment fileListFragment = getListOfFilesFragment();
413 if (fileListFragment != null) {
414 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
);
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);
670 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
672 Log_OC
.d(TAG
, "onSaveInstanceState() end");
678 protected void onResume() {
680 Log_OC
.e(TAG
, "onResume() start");
682 // Listen for sync messages
683 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
684 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
685 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
686 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
687 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
688 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
689 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
690 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
691 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
693 // Listen for upload messages
694 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
695 mUploadFinishReceiver
= new UploadFinishReceiver();
696 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
698 // Listen for download messages
699 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
700 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
701 mDownloadFinishReceiver
= new DownloadFinishReceiver();
702 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
704 // Listen for messages from the OperationsService
706 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
707 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
708 mOperationsServiceReceiver = new OperationsServiceReceiver();
709 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
712 Log_OC
.d(TAG
, "onResume() end");
717 protected void onPause() {
719 Log_OC
.e(TAG
, "onPause() start");
720 if (mSyncBroadcastReceiver
!= null
) {
721 unregisterReceiver(mSyncBroadcastReceiver
);
722 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
723 mSyncBroadcastReceiver
= null
;
725 if (mUploadFinishReceiver
!= null
) {
726 unregisterReceiver(mUploadFinishReceiver
);
727 mUploadFinishReceiver
= null
;
729 if (mDownloadFinishReceiver
!= null
) {
730 unregisterReceiver(mDownloadFinishReceiver
);
731 mDownloadFinishReceiver
= null
;
734 if (mOperationsServiceReceiver != null) {
735 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
736 mOperationsServiceReceiver = null;
739 Log_OC
.d(TAG
, "onPause() end");
744 protected Dialog
onCreateDialog(int id
) {
745 Dialog dialog
= null
;
746 AlertDialog
.Builder builder
;
748 case DIALOG_SHORT_WAIT
: {
749 ProgressDialog working_dialog
= new ProgressDialog(this);
750 working_dialog
.setMessage(getResources().getString(
751 R
.string
.wait_a_moment
));
752 working_dialog
.setIndeterminate(true
);
753 working_dialog
.setCancelable(false
);
754 dialog
= working_dialog
;
757 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
759 String
[] items
= null
;
761 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
762 getString(R
.string
.actionbar_upload_from_apps
),
763 getString(R
.string
.actionbar_failed_instant_upload
) };
765 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
766 getString(R
.string
.actionbar_upload_from_apps
) };
768 if (InstantUploadActivity
.IS_ENABLED
)
773 builder
= new AlertDialog
.Builder(this);
774 builder
.setTitle(R
.string
.actionbar_upload
);
775 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
776 public void onClick(DialogInterface dialog
, int item
) {
779 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
780 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
781 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
783 // TODO create and handle new fragment
784 // LocalFileListFragment
786 } else if (item
== 1) {
787 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
788 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
789 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
790 ACTION_SELECT_CONTENT_FROM_APPS
);
791 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
792 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
793 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
794 startActivity(action
);
798 dialog
= builder
.create();
801 case DIALOG_CERT_NOT_SAVED
: {
802 builder
= new AlertDialog
.Builder(this);
803 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
804 builder
.setCancelable(false
);
805 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
807 public void onClick(DialogInterface dialog
, int which
) {
811 dialog
= builder
.create();
823 * Translates a content URI of an image to a physical path
825 * @param uri The URI to resolve
826 * @return The path to the image or null if it could not be found
828 public String
getPath(Uri uri
) {
829 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
830 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
831 if (cursor
!= null
) {
832 int column_index
= cursor
833 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
834 cursor
.moveToFirst();
835 return cursor
.getString(column_index
);
841 * Pushes a directory to the drop down list
842 * @param directory to push
843 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
845 public void pushDirname(OCFile directory
) {
846 if(!directory
.isFolder()){
847 throw new IllegalArgumentException("Only directories may be pushed!");
849 mDirectories
.insert(directory
.getFileName(), 0);
854 * Pops a directory name from the drop down list
855 * @return True, unless the stack is empty
857 public boolean popDirname() {
858 mDirectories
.remove(mDirectories
.getItem(0));
859 return !mDirectories
.isEmpty();
862 // Custom array adapter to override text colors
863 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
865 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
869 public View
getView(int position
, View convertView
, ViewGroup parent
) {
870 View v
= super.getView(position
, convertView
, parent
);
872 ((TextView
) v
).setTextColor(getResources().getColorStateList(
873 android
.R
.color
.white
));
875 fixRoot((TextView
) v
);
879 public View
getDropDownView(int position
, View convertView
,
881 View v
= super.getDropDownView(position
, convertView
, parent
);
883 ((TextView
) v
).setTextColor(getResources().getColorStateList(
884 android
.R
.color
.white
));
886 fixRoot((TextView
) v
);
890 private void fixRoot(TextView v
) {
891 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
892 v
.setText(R
.string
.default_display_name_for_root_folder
);
898 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
901 * {@link BroadcastReceiver} to enable syncing feedback in UI
904 public void onReceive(Context context
, Intent intent
) {
906 String event
= intent
.getAction();
907 Log_OC
.d(TAG
, "Received broadcast " + event
);
908 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
909 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
910 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
911 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
915 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
916 mSyncInProgress
= true
;
919 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
920 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
922 if (currentDir
== null
) {
923 // current folder was removed from the server
924 Toast
.makeText( FileDisplayActivity
.this,
925 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
931 if (currentFile
== null
&& !getFile().isFolder()) {
932 // currently selected file was removed in the server, and now we know it
933 cleanSecondFragment();
934 currentFile
= currentDir
;
938 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
939 OCFileListFragment fileListFragment = getListOfFilesFragment();
940 if (fileListFragment != null) {
941 fileListFragment.listDirectory(currentDir);
945 setFile(currentFile
);
948 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
951 if (synchResult != null &&
952 synchResult.isSuccess() &&
953 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
954 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
956 !mRefreshSharesInProgress &&
957 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
964 removeStickyBroadcast(intent
);
965 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
966 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
969 if (synchResult
!= null
) {
970 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
971 mLastSslUntrustedServerResult
= synchResult
;
974 } catch (RuntimeException e
) {
975 // avoid app crashes after changing the serial id of RemoteOperationResult
976 // in owncloud library with broadcast notifications pending to process
977 removeStickyBroadcast(intent
);
984 * Once the file upload has finished -> update view
986 private class UploadFinishReceiver
extends BroadcastReceiver
{
988 * Once the file upload has finished -> update view
989 * @author David A. Velasco
990 * {@link BroadcastReceiver} to enable upload feedback in UI
993 public void onReceive(Context context
, Intent intent
) {
994 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
995 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
996 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
997 OCFile currentDir
= getCurrentDir();
998 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
999 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1001 if (sameAccount
&& isDescendant
) {
1003 refeshListOfFilesFragment();
1007 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1008 boolean renamedInUpload
= getFile().getRemotePath().
1009 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1010 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1012 FileFragment details
= getSecondFragment();
1013 boolean detailFragmentIsShown
= (details
!= null
&&
1014 details
instanceof FileDetailFragment
);
1016 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1017 if (uploadWasFine
) {
1018 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1020 if (renamedInUpload
) {
1021 String newName
= (new File(uploadedRemotePath
)).getName();
1022 Toast msg
= Toast
.makeText(
1025 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1030 ((FileDetailFragment
)details
).updateFileDetails(false
, false
);
1032 // Force the preview if the file is an image
1033 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1034 startImagePreview(getFile());
1035 } // TODO what about other kind of previews?
1038 removeStickyBroadcast(intent
);
1046 * Class waiting for broadcast events from the {@link FielDownloader} service.
1048 * Updates the UI when a download is started or finished, provided that it is relevant for the
1051 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1053 public void onReceive(Context context
, Intent intent
) {
1054 boolean sameAccount
= isSameAccount(context
, intent
);
1055 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1056 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1058 if (sameAccount
&& isDescendant
) {
1060 refeshListOfFilesFragment();
1062 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1065 if (mWaitingToSend
!= null
) {
1066 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1067 if (mWaitingToSend
.isDown()) {
1068 sendDownloadedFile();
1072 removeStickyBroadcast(intent
);
1075 private boolean isDescendant(String downloadedRemotePath
) {
1076 OCFile currentDir
= getCurrentDir();
1077 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1080 private boolean isSameAccount(Context context
, Intent intent
) {
1081 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1082 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1088 * Class waiting for broadcast events from the {@link OperationsService}.
1090 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1091 * operation performed in {@link OperationsService}.
1093 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1094 * probably all the operations associated to the app model.
1096 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1099 public void onReceive(Context context
, Intent intent
) {
1100 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1102 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1103 //mRefreshSharesInProgress = false;
1105 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1106 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1107 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1108 && getStorageManager() != null
1111 refeshListOfFilesFragment();
1114 if ((getSharesResult
!= null
) &&
1115 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1116 mLastSslUntrustedServerResult
= getSharesResult
;
1117 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1120 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1127 public void browseToRoot() {
1128 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1129 if (listOfFiles
!= null
) { // should never be null, indeed
1130 while (mDirectories
.getCount() > 1) {
1133 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1134 listOfFiles
.listDirectory(root
);
1135 setFile(listOfFiles
.getCurrentFile());
1136 startSyncFolderOperation(root
);
1138 cleanSecondFragment();
1142 public void browseTo(OCFile folder
) {
1143 if (folder
== null
|| !folder
.isFolder()) {
1144 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1146 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1147 if (listOfFiles
!= null
) {
1148 setNavigationListWithFolder(folder
);
1149 listOfFiles
.listDirectory(folder
);
1150 setFile(listOfFiles
.getCurrentFile());
1151 startSyncFolderOperation(folder
);
1153 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1155 cleanSecondFragment();
1162 * Updates action bar and second fragment, if in dual pane mode.
1165 public void onBrowsedDownTo(OCFile directory
) {
1166 pushDirname(directory
);
1167 cleanSecondFragment();
1170 startSyncFolderOperation(directory
);
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
);
1221 public void onFileStateChanged() {
1223 refeshListOfFilesFragment();
1224 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1230 protected ServiceConnection
newTransferenceServiceConnection() {
1231 return new ListServiceConnection();
1234 /** Defines callbacks for service binding, passed to bindService() */
1235 private class ListServiceConnection
implements ServiceConnection
{
1238 public void onServiceConnected(ComponentName component
, IBinder service
) {
1239 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1240 Log_OC
.d(TAG
, "Download service connected");
1241 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1242 if (mWaitingToPreview
!= null
) {
1243 requestForDownload();
1246 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1247 Log_OC
.d(TAG
, "Upload service connected");
1248 mUploaderBinder
= (FileUploaderBinder
) service
;
1252 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1253 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1254 if (listOfFiles
!= null
) {
1255 listOfFiles
.listDirectory();
1257 FileFragment secondFragment
= getSecondFragment();
1258 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1259 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1260 detailFragment
.listenForTransferProgress();
1261 detailFragment
.updateFileDetails(false
, false
);
1266 public void onServiceDisconnected(ComponentName component
) {
1267 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1268 Log_OC
.d(TAG
, "Download service disconnected");
1269 mDownloaderBinder
= null
;
1270 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1271 Log_OC
.d(TAG
, "Upload service disconnected");
1272 mUploaderBinder
= null
;
1280 * Launch an intent to request the PIN code to the user before letting him use the app
1282 private void requestPinCode() {
1283 boolean pinStart
= false
;
1284 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1285 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1287 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1288 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1295 public void onSavedCertificate() {
1296 startSyncFolderOperation(getCurrentDir());
1301 public void onFailedSavingCertificate() {
1302 showDialog(DIALOG_CERT_NOT_SAVED
);
1306 public void onCancelCertificate() {
1311 * Updates the view associated to the activity after the finish of some operation over files
1312 * in the current account.
1314 * @param operation Removal operation performed.
1315 * @param result Result of the removal.
1318 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1319 super.onRemoteOperationFinish(operation
, result
);
1321 if (operation
instanceof RemoveFileOperation
) {
1322 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1324 } else if (operation
instanceof RenameFileOperation
) {
1325 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1327 } else if (operation
instanceof SynchronizeFileOperation
) {
1328 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1330 } else if (operation
instanceof CreateFolderOperation
) {
1331 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1333 } else if (operation
instanceof CreateShareOperation
) {
1334 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1336 } else if (operation
instanceof UnshareLinkOperation
) {
1337 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1344 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1345 if (result
.isSuccess()) {
1346 refreshShowDetails();
1348 refeshListOfFilesFragment();
1354 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1355 if (result
.isSuccess()) {
1356 refreshShowDetails();
1358 refeshListOfFilesFragment();
1360 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1361 cleanSecondFragment();
1363 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 FileFragment second
= getSecondFragment();
1399 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1400 cleanSecondFragment();
1402 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1404 refeshListOfFilesFragment();
1409 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1411 if (result
.isSslRecoverableException()) {
1412 mLastSslUntrustedServerResult
= result
;
1413 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1420 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1422 * @param operation Creation operation performed.
1423 * @param result Result of the creation.
1425 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1426 if (result
.isSuccess()) {
1427 dismissLoadingDialog();
1429 refeshListOfFilesFragment();
1433 dismissLoadingDialog();
1434 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1435 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1438 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1441 } catch (NotFoundException e
) {
1442 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1450 * Updates the view associated to the activity after the finish of an operation trying to rename a
1453 * @param operation Renaming operation performed.
1454 * @param result Result of the renaming.
1456 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1457 dismissLoadingDialog();
1458 OCFile renamedFile
= operation
.getFile();
1459 if (result
.isSuccess()) {
1460 FileFragment details
= getSecondFragment();
1461 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1462 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1464 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1466 refeshListOfFilesFragment();
1471 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1472 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1474 // TODO throw again the new rename dialog
1475 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1476 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1479 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1481 if (result
.isSslRecoverableException()) {
1482 mLastSslUntrustedServerResult
= result
;
1483 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1489 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1490 dismissLoadingDialog();
1491 OCFile syncedFile
= operation
.getLocalFile();
1492 if (!result
.isSuccess()) {
1493 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1494 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1495 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1496 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1502 if (operation
.transferWasRequested()) {
1504 refeshListOfFilesFragment();
1506 onTransferStateChanged(syncedFile
, true
, true
);
1509 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1520 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1521 FileFragment details
= getSecondFragment();
1522 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1523 if (downloading
|| uploading
) {
1524 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1526 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1532 public void onDismiss(EditNameDialog dialog
) {
1533 if (dialog
.getResult()) {
1534 String newDirectoryName
= dialog
.getNewFilename().trim();
1535 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1536 if (newDirectoryName
.length() > 0) {
1537 String path
= getCurrentDir().getRemotePath();
1540 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1541 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1542 operation
.execute( getAccount(),
1543 FileDisplayActivity
.this,
1544 FileDisplayActivity
.this,
1546 FileDisplayActivity
.this);
1548 showLoadingDialog();
1554 private void requestForDownload() {
1555 Account account
= getAccount();
1556 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1557 Intent i
= new Intent(this, FileDownloader
.class);
1558 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1559 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1565 private OCFile
getCurrentDir() {
1566 OCFile file
= getFile();
1568 if (file
.isFolder()) {
1570 } else if (getStorageManager() != null
) {
1571 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1572 return getStorageManager().getFileByPath(parentPath
);
1578 public void startSyncFolderOperation(OCFile folder
) {
1579 long currentSyncTime
= System
.currentTimeMillis();
1581 mSyncInProgress
= true
;
1583 // perform folder synchronization
1584 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1587 getFileOperationsHelper().isSharedSupported(),
1588 getStorageManager(),
1590 getApplicationContext()
1592 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1594 setSupportProgressBarIndeterminateVisibility(true
);
1598 private void startGetShares() {
1599 // Get shared files/folders
1600 Intent intent = new Intent(this, OperationsService.class);
1601 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1602 startService(intent);
1604 mRefreshSharesInProgress = true;
1609 * Show untrusted cert dialog
1611 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1612 // Show a dialog with the certificate info
1613 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1614 FragmentManager fm
= getSupportFragmentManager();
1615 FragmentTransaction ft
= fm
.beginTransaction();
1616 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1619 private void requestForDownload(OCFile file
) {
1620 Account account
= getAccount();
1621 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1622 Intent i
= new Intent(this, FileDownloader
.class);
1623 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1624 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1629 private void sendDownloadedFile(){
1630 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1631 mWaitingToSend
= null
;
1636 * Requests the download of the received {@link OCFile} , updates the UI
1637 * to monitor the download progress and prepares the activity to send the file
1638 * when the download finishes.
1640 * @param file {@link OCFile} to download and preview.
1642 public void startDownloadForSending(OCFile file
) {
1643 mWaitingToSend
= file
;
1644 requestForDownload(mWaitingToSend
);
1645 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1646 updateFragmentsVisibility(hasSecondFragment
);
1650 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1652 * @param file Image {@link OCFile} to show.
1654 public void startImagePreview(OCFile file
) {
1655 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1656 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1657 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1658 startActivity(showDetailsIntent
);
1662 * Stars the preview of an already down media {@link OCFile}.
1664 * @param file Media {@link OCFile} to preview.
1665 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1666 * @param autoplay When 'true', the playback will start without user interactions.
1668 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1669 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1670 setSecondFragment(mediaFragment
);
1671 updateFragmentsVisibility(true
);
1672 updateNavigationElementsInActionBar(file
);
1677 * Requests the download of the received {@link OCFile} , updates the UI
1678 * to monitor the download progress and prepares the activity to preview
1679 * or open the file when the download finishes.
1681 * @param file {@link OCFile} to download and preview.
1683 public void startDownloadForPreview(OCFile file
) {
1684 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1685 setSecondFragment(detailFragment
);
1686 mWaitingToPreview
= file
;
1687 requestForDownload();
1688 updateFragmentsVisibility(true
);
1689 updateNavigationElementsInActionBar(file
);
1694 public void cancelTransference(OCFile file
) {
1695 Account account
= getAccount();
1696 if (mDownloaderBinder
!= null
&& mDownloaderBinder
.isDownloading(account
, file
)) {
1697 mDownloaderBinder
.cancel(account
, file
);
1698 onTransferStateChanged(file
, false
, false
);
1700 } else if (mUploaderBinder
!= null
&& mUploaderBinder
.isUploading(account
, file
)) {
1701 mUploaderBinder
.cancel(account
, file
);
1702 if (!file
.fileExists()) {
1703 cleanSecondFragment();
1706 onTransferStateChanged(file
, false
, false
);