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 refreshListOfFilesFragment();
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
);
410 protected void refreshListOfFilesFragment() {
411 OCFileListFragment fileListFragment
= getListOfFilesFragment();
412 if (fileListFragment
!= null
) {
413 fileListFragment
.listDirectory();
417 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
418 FileFragment secondFragment
= getSecondFragment();
419 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
420 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
421 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
422 OCFile fileInFragment
= detailsFragment
.getFile();
423 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
424 // the user browsed to other file ; forget the automatic preview
425 mWaitingToPreview
= null
;
427 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
428 // grant that the right panel updates the progress bar
429 detailsFragment
.listenForTransferProgress();
430 detailsFragment
.updateFileDetails(true
, false
);
432 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
433 // update the right panel
434 boolean detailsFragmentChanged
= false
;
437 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
438 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
439 startMediaPreview(mWaitingToPreview
, 0, true
);
440 detailsFragmentChanged
= true
;
442 getFileOperationsHelper().openFile(mWaitingToPreview
);
445 mWaitingToPreview
= null
;
447 if (!detailsFragmentChanged
) {
448 detailsFragment
.updateFileDetails(false
, (success
));
455 public boolean onCreateOptionsMenu(Menu menu
) {
456 MenuInflater inflater
= getSherlock().getMenuInflater();
457 inflater
.inflate(R
.menu
.main_menu
, menu
);
462 public boolean onOptionsItemSelected(MenuItem item
) {
463 boolean retval
= true
;
464 switch (item
.getItemId()) {
465 case R
.id
.action_create_dir
: {
466 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
467 dialog
.show(getSupportFragmentManager(), "createdirdialog");
470 case R
.id
.action_sync_account
: {
471 startSynchronization();
474 case R
.id
.action_upload
: {
475 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
478 case R
.id
.action_settings
: {
479 Intent settingsIntent
= new Intent(this, Preferences
.class);
480 startActivity(settingsIntent
);
483 case android
.R
.id
.home
: {
484 FileFragment second
= getSecondFragment();
485 OCFile currentDir
= getCurrentDir();
486 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
487 (second
!= null
&& second
.getFile() != null
)) {
494 retval
= super.onOptionsItemSelected(item
);
499 private void startSynchronization() {
500 Log_OC
.e(TAG
, "Got to start sync");
501 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
502 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
503 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
504 Bundle bundle
= new Bundle();
505 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
506 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
507 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
508 ContentResolver
.requestSync(
510 MainApp
.getAuthority(), bundle
);
512 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
513 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
514 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
515 builder
.setExpedited(true
);
516 builder
.setManual(true
);
518 SyncRequest request
= builder
.build();
519 ContentResolver
.requestSync(request
);
525 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
526 if (itemPosition
!= 0) {
527 String targetPath
= "";
528 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
529 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
531 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
532 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
533 if (targetFolder
!= null
) {
534 browseTo(targetFolder
);
537 // the next operation triggers a new call to this method, but it's necessary to
538 // ensure that the name exposed in the action bar is the current directory when the
539 // user selected it in the navigation list
540 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
541 getSupportActionBar().setSelectedNavigationItem(0);
547 * Called, when the user selected something for uploading
549 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
550 super.onActivityResult(requestCode
, resultCode
, data
);
552 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
553 requestSimpleUpload(data
, resultCode
);
555 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
556 requestMultipleUpload(data
, resultCode
);
561 private void requestMultipleUpload(Intent data
, int resultCode
) {
562 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
563 if (filePaths
!= null
) {
564 String
[] remotePaths
= new String
[filePaths
.length
];
565 String remotePathBase
= "";
566 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
567 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
569 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
570 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
571 for (int j
= 0; j
< remotePaths
.length
; j
++) {
572 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
575 Intent i
= new Intent(this, FileUploader
.class);
576 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
577 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
578 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
579 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
580 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
581 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
585 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
586 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
593 private void requestSimpleUpload(Intent data
, int resultCode
) {
594 String filepath
= null
;
596 Uri selectedImageUri
= data
.getData();
598 String filemanagerstring
= selectedImageUri
.getPath();
599 String selectedImagePath
= getPath(selectedImageUri
);
601 if (selectedImagePath
!= null
)
602 filepath
= selectedImagePath
;
604 filepath
= filemanagerstring
;
606 } catch (Exception e
) {
607 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
611 if (filepath
== null
) {
612 Log_OC
.e(TAG
, "Couldnt resolve path to file");
613 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
619 Intent i
= new Intent(this, FileUploader
.class);
620 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
622 String remotepath
= new String();
623 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
624 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
626 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
627 remotepath
+= OCFile
.PATH_SEPARATOR
;
628 remotepath
+= new File(filepath
).getName();
630 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
631 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
632 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
633 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
634 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
639 public void onBackPressed() {
640 OCFileListFragment listOfFiles
= getListOfFilesFragment();
641 if (mDualPane
|| getSecondFragment() == null
) {
642 if (listOfFiles
!= null
) { // should never be null, indeed
643 if (mDirectories
.getCount() <= 1) {
647 int levelsUp
= listOfFiles
.onBrowseUp();
648 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
653 if (listOfFiles
!= null
) { // should never be null, indeed
654 setFile(listOfFiles
.getCurrentFile());
656 cleanSecondFragment();
661 protected void onSaveInstanceState(Bundle outState
) {
662 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
663 Log_OC
.e(TAG
, "onSaveInstanceState() start");
664 super.onSaveInstanceState(outState
);
665 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
666 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
667 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
668 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
670 Log_OC
.d(TAG
, "onSaveInstanceState() end");
676 protected void onResume() {
678 Log_OC
.e(TAG
, "onResume() start");
680 // Listen for sync messages
681 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
682 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
683 //syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
684 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
685 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
686 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
687 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
688 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
689 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
691 // Listen for upload messages
692 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
693 mUploadFinishReceiver
= new UploadFinishReceiver();
694 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
696 // Listen for download messages
697 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
698 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
699 mDownloadFinishReceiver
= new DownloadFinishReceiver();
700 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
702 // Listen for messages from the OperationsService
704 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
705 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
706 mOperationsServiceReceiver = new OperationsServiceReceiver();
707 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
710 Log_OC
.d(TAG
, "onResume() end");
715 protected void onPause() {
717 Log_OC
.e(TAG
, "onPause() start");
718 if (mSyncBroadcastReceiver
!= null
) {
719 unregisterReceiver(mSyncBroadcastReceiver
);
720 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
721 mSyncBroadcastReceiver
= null
;
723 if (mUploadFinishReceiver
!= null
) {
724 unregisterReceiver(mUploadFinishReceiver
);
725 mUploadFinishReceiver
= null
;
727 if (mDownloadFinishReceiver
!= null
) {
728 unregisterReceiver(mDownloadFinishReceiver
);
729 mDownloadFinishReceiver
= null
;
732 if (mOperationsServiceReceiver != null) {
733 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
734 mOperationsServiceReceiver = null;
737 Log_OC
.d(TAG
, "onPause() end");
742 protected Dialog
onCreateDialog(int id
) {
743 Dialog dialog
= null
;
744 AlertDialog
.Builder builder
;
746 case DIALOG_SHORT_WAIT
: {
747 ProgressDialog working_dialog
= new ProgressDialog(this);
748 working_dialog
.setMessage(getResources().getString(
749 R
.string
.wait_a_moment
));
750 working_dialog
.setIndeterminate(true
);
751 working_dialog
.setCancelable(false
);
752 dialog
= working_dialog
;
755 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
757 String
[] items
= null
;
759 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
760 getString(R
.string
.actionbar_upload_from_apps
),
761 getString(R
.string
.actionbar_failed_instant_upload
) };
763 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
764 getString(R
.string
.actionbar_upload_from_apps
) };
766 if (InstantUploadActivity
.IS_ENABLED
)
771 builder
= new AlertDialog
.Builder(this);
772 builder
.setTitle(R
.string
.actionbar_upload
);
773 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
774 public void onClick(DialogInterface dialog
, int item
) {
777 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
778 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
779 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
781 // TODO create and handle new fragment
782 // LocalFileListFragment
784 } else if (item
== 1) {
785 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
786 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
787 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
788 ACTION_SELECT_CONTENT_FROM_APPS
);
789 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
790 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
791 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
792 startActivity(action
);
796 dialog
= builder
.create();
799 case DIALOG_CERT_NOT_SAVED
: {
800 builder
= new AlertDialog
.Builder(this);
801 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
802 builder
.setCancelable(false
);
803 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
805 public void onClick(DialogInterface dialog
, int which
) {
809 dialog
= builder
.create();
821 * Translates a content URI of an image to a physical path
823 * @param uri The URI to resolve
824 * @return The path to the image or null if it could not be found
826 public String
getPath(Uri uri
) {
827 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
828 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
829 if (cursor
!= null
) {
830 int column_index
= cursor
831 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
832 cursor
.moveToFirst();
833 return cursor
.getString(column_index
);
839 * Pushes a directory to the drop down list
840 * @param directory to push
841 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
843 public void pushDirname(OCFile directory
) {
844 if(!directory
.isFolder()){
845 throw new IllegalArgumentException("Only directories may be pushed!");
847 mDirectories
.insert(directory
.getFileName(), 0);
852 * Pops a directory name from the drop down list
853 * @return True, unless the stack is empty
855 public boolean popDirname() {
856 mDirectories
.remove(mDirectories
.getItem(0));
857 return !mDirectories
.isEmpty();
860 // Custom array adapter to override text colors
861 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
863 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
867 public View
getView(int position
, View convertView
, ViewGroup parent
) {
868 View v
= super.getView(position
, convertView
, parent
);
870 ((TextView
) v
).setTextColor(getResources().getColorStateList(
871 android
.R
.color
.white
));
873 fixRoot((TextView
) v
);
877 public View
getDropDownView(int position
, View convertView
,
879 View v
= super.getDropDownView(position
, convertView
, parent
);
881 ((TextView
) v
).setTextColor(getResources().getColorStateList(
882 android
.R
.color
.white
));
884 fixRoot((TextView
) v
);
888 private void fixRoot(TextView v
) {
889 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
890 v
.setText(R
.string
.default_display_name_for_root_folder
);
896 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
899 * {@link BroadcastReceiver} to enable syncing feedback in UI
902 public void onReceive(Context context
, Intent intent
) {
904 String event
= intent
.getAction();
905 Log_OC
.d(TAG
, "Received broadcast " + event
);
906 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
907 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
908 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
909 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
913 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
914 mSyncInProgress
= true
;
917 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
918 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
920 if (currentDir
== null
) {
921 // current folder was removed from the server
922 Toast
.makeText( FileDisplayActivity
.this,
923 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
929 if (currentFile
== null
&& !getFile().isFolder()) {
930 // currently selected file was removed in the server, and now we know it
931 cleanSecondFragment();
932 currentFile
= currentDir
;
936 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
937 OCFileListFragment fileListFragment
= getListOfFilesFragment();
938 if (fileListFragment
!= null
) {
939 fileListFragment
.listDirectory(currentDir
);
943 setFile(currentFile
);
946 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
949 if (synchResult != null &&
950 synchResult.isSuccess() &&
951 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
952 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
954 !mRefreshSharesInProgress &&
955 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
962 removeStickyBroadcast(intent
);
963 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
964 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
967 if (synchResult
!= null
) {
968 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
969 mLastSslUntrustedServerResult
= synchResult
;
972 } catch (RuntimeException e
) {
973 // avoid app crashes after changing the serial id of RemoteOperationResult
974 // in owncloud library with broadcast notifications pending to process
975 removeStickyBroadcast(intent
);
982 * Once the file upload has finished -> update view
984 private class UploadFinishReceiver
extends BroadcastReceiver
{
986 * Once the file upload has finished -> update view
987 * @author David A. Velasco
988 * {@link BroadcastReceiver} to enable upload feedback in UI
991 public void onReceive(Context context
, Intent intent
) {
992 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
993 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
994 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
995 OCFile currentDir
= getCurrentDir();
996 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
997 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
999 if (sameAccount
&& isDescendant
) {
1001 refreshListOfFilesFragment();
1005 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1006 boolean renamedInUpload
= getFile().getRemotePath().
1007 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1008 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1010 FileFragment details
= getSecondFragment();
1011 boolean detailFragmentIsShown
= (details
!= null
&&
1012 details
instanceof FileDetailFragment
);
1014 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1015 if (uploadWasFine
) {
1016 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1018 if (renamedInUpload
) {
1019 String newName
= (new File(uploadedRemotePath
)).getName();
1020 Toast msg
= Toast
.makeText(
1023 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1028 ((FileDetailFragment
)details
).updateFileDetails(false
, false
);
1030 // Force the preview if the file is an image
1031 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1032 startImagePreview(getFile());
1033 } // TODO what about other kind of previews?
1036 removeStickyBroadcast(intent
);
1044 * Class waiting for broadcast events from the {@link FielDownloader} service.
1046 * Updates the UI when a download is started or finished, provided that it is relevant for the
1049 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1051 public void onReceive(Context context
, Intent intent
) {
1052 boolean sameAccount
= isSameAccount(context
, intent
);
1053 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1054 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1056 if (sameAccount
&& isDescendant
) {
1058 refreshListOfFilesFragment();
1060 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1063 if (mWaitingToSend
!= null
) {
1064 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1065 if (mWaitingToSend
.isDown()) {
1066 sendDownloadedFile();
1070 removeStickyBroadcast(intent
);
1073 private boolean isDescendant(String downloadedRemotePath
) {
1074 OCFile currentDir
= getCurrentDir();
1075 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1078 private boolean isSameAccount(Context context
, Intent intent
) {
1079 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1080 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1086 * Class waiting for broadcast events from the {@link OperationsService}.
1088 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1089 * operation performed in {@link OperationsService}.
1091 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1092 * probably all the operations associated to the app model.
1094 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1097 public void onReceive(Context context
, Intent intent
) {
1098 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1100 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1101 //mRefreshSharesInProgress = false;
1103 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1104 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1105 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1106 && getStorageManager() != null
1109 refeshListOfFilesFragment();
1112 if ((getSharesResult
!= null
) &&
1113 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1114 mLastSslUntrustedServerResult
= getSharesResult
;
1115 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1118 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1125 public void browseToRoot() {
1126 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1127 if (listOfFiles
!= null
) { // should never be null, indeed
1128 while (mDirectories
.getCount() > 1) {
1131 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1132 listOfFiles
.listDirectory(root
);
1133 setFile(listOfFiles
.getCurrentFile());
1134 startSyncFolderOperation(root
);
1136 cleanSecondFragment();
1140 public void browseTo(OCFile folder
) {
1141 if (folder
== null
|| !folder
.isFolder()) {
1142 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1144 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1145 if (listOfFiles
!= null
) {
1146 setNavigationListWithFolder(folder
);
1147 listOfFiles
.listDirectory(folder
);
1148 setFile(listOfFiles
.getCurrentFile());
1149 startSyncFolderOperation(folder
);
1151 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1153 cleanSecondFragment();
1160 * Updates action bar and second fragment, if in dual pane mode.
1163 public void onBrowsedDownTo(OCFile directory
) {
1164 pushDirname(directory
);
1165 cleanSecondFragment();
1168 startSyncFolderOperation(directory
);
1173 * Shows the information of the {@link OCFile} received as a
1174 * parameter in the second fragment.
1176 * @param file {@link OCFile} whose details will be shown
1179 public void showDetails(OCFile file
) {
1180 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1181 setSecondFragment(detailFragment
);
1182 updateFragmentsVisibility(true
);
1183 updateNavigationElementsInActionBar(file
);
1191 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1192 ActionBar actionBar
= getSupportActionBar();
1193 if (chosenFile
== null
|| mDualPane
) {
1194 // only list of files - set for browsing through folders
1195 OCFile currentDir
= getCurrentDir();
1196 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1197 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1198 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1200 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1202 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1203 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1206 actionBar
.setDisplayHomeAsUpEnabled(true
);
1207 actionBar
.setDisplayShowTitleEnabled(true
);
1208 actionBar
.setTitle(chosenFile
.getFileName());
1209 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1214 // TODO: delete this method??
1220 // public void onFileStateChanged() {
1221 // /* TODO WIP COMMENT
1222 // refeshListOfFilesFragment();
1223 // 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();
1347 refreshListOfFilesFragment();
1352 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1353 if (result
.isSuccess()) {
1354 refreshShowDetails();
1355 refreshListOfFilesFragment();
1357 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1358 cleanSecondFragment();
1359 refreshListOfFilesFragment();
1363 private void refreshShowDetails() {
1364 FileFragment details
= getSecondFragment();
1365 if (details
!= null
) {
1366 OCFile file
= details
.getFile();
1368 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1369 if (details
instanceof PreviewMediaFragment
) {
1370 // Refresh OCFile of the fragment
1371 ((PreviewMediaFragment
) details
).updateFile(file
);
1376 invalidateOptionsMenu();
1381 * Updates the view associated to the activity after the finish of an operation trying to remove a
1384 * @param operation Removal operation performed.
1385 * @param result Result of the removal.
1387 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1388 dismissLoadingDialog();
1389 if (result
.isSuccess()) {
1390 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1392 OCFile removedFile
= operation
.getFile();
1393 FileFragment second
= getSecondFragment();
1394 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1395 cleanSecondFragment();
1397 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1398 refreshListOfFilesFragment();
1402 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1404 if (result
.isSslRecoverableException()) {
1405 mLastSslUntrustedServerResult
= result
;
1406 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1413 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1415 * @param operation Creation operation performed.
1416 * @param result Result of the creation.
1418 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1419 if (result
.isSuccess()) {
1420 dismissLoadingDialog();
1421 refreshListOfFilesFragment();
1423 dismissLoadingDialog();
1424 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1425 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1428 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1431 } catch (NotFoundException e
) {
1432 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1440 * Updates the view associated to the activity after the finish of an operation trying to rename a
1443 * @param operation Renaming operation performed.
1444 * @param result Result of the renaming.
1446 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1447 dismissLoadingDialog();
1448 OCFile renamedFile
= operation
.getFile();
1449 if (result
.isSuccess()) {
1450 FileFragment details
= getSecondFragment();
1451 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1452 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1454 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1455 refreshListOfFilesFragment();
1459 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1460 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1462 // TODO throw again the new rename dialog
1463 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1464 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1467 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1469 if (result
.isSslRecoverableException()) {
1470 mLastSslUntrustedServerResult
= result
;
1471 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1477 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1478 dismissLoadingDialog();
1479 OCFile syncedFile
= operation
.getLocalFile();
1480 if (!result
.isSuccess()) {
1481 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1482 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1483 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1484 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1490 if (operation
.transferWasRequested()) {
1491 /* WIP: delete this refresh?
1492 * refreshListOfFilesFragment();
1494 onTransferStateChanged(syncedFile
, true
, true
);
1497 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1508 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1509 FileFragment details
= getSecondFragment();
1510 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1511 if (downloading
|| uploading
) {
1512 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1514 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1520 public void onDismiss(EditNameDialog dialog
) {
1521 if (dialog
.getResult()) {
1522 String newDirectoryName
= dialog
.getNewFilename().trim();
1523 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1524 if (newDirectoryName
.length() > 0) {
1525 String path
= getCurrentDir().getRemotePath();
1528 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1529 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1530 operation
.execute( getAccount(),
1531 FileDisplayActivity
.this,
1532 FileDisplayActivity
.this,
1534 FileDisplayActivity
.this);
1536 showLoadingDialog();
1542 private void requestForDownload() {
1543 Account account
= getAccount();
1544 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1545 Intent i
= new Intent(this, FileDownloader
.class);
1546 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1547 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1553 private OCFile
getCurrentDir() {
1554 OCFile file
= getFile();
1556 if (file
.isFolder()) {
1558 } else if (getStorageManager() != null
) {
1559 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1560 return getStorageManager().getFileByPath(parentPath
);
1566 public void startSyncFolderOperation(OCFile folder
) {
1567 long currentSyncTime
= System
.currentTimeMillis();
1569 mSyncInProgress
= true
;
1571 // perform folder synchronization
1572 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1575 getFileOperationsHelper().isSharedSupported(),
1576 getStorageManager(),
1578 getApplicationContext()
1580 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1582 setSupportProgressBarIndeterminateVisibility(true
);
1586 private void startGetShares() {
1587 // Get shared files/folders
1588 Intent intent = new Intent(this, OperationsService.class);
1589 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1590 startService(intent);
1592 mRefreshSharesInProgress = true;
1597 * Show untrusted cert dialog
1599 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1600 // Show a dialog with the certificate info
1601 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1602 FragmentManager fm
= getSupportFragmentManager();
1603 FragmentTransaction ft
= fm
.beginTransaction();
1604 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1607 private void requestForDownload(OCFile file
) {
1608 Account account
= getAccount();
1609 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1610 Intent i
= new Intent(this, FileDownloader
.class);
1611 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1612 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1617 private void sendDownloadedFile(){
1618 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1619 mWaitingToSend
= null
;
1624 * Requests the download of the received {@link OCFile} , updates the UI
1625 * to monitor the download progress and prepares the activity to send the file
1626 * when the download finishes.
1628 * @param file {@link OCFile} to download and preview.
1630 public void startDownloadForSending(OCFile file
) {
1631 mWaitingToSend
= file
;
1632 requestForDownload(mWaitingToSend
);
1633 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1634 updateFragmentsVisibility(hasSecondFragment
);
1638 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1640 * @param file Image {@link OCFile} to show.
1642 public void startImagePreview(OCFile file
) {
1643 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1644 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1645 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1646 startActivity(showDetailsIntent
);
1650 * Stars the preview of an already down media {@link OCFile}.
1652 * @param file Media {@link OCFile} to preview.
1653 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1654 * @param autoplay When 'true', the playback will start without user interactions.
1656 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1657 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1658 setSecondFragment(mediaFragment
);
1659 updateFragmentsVisibility(true
);
1660 updateNavigationElementsInActionBar(file
);
1665 * Requests the download of the received {@link OCFile} , updates the UI
1666 * to monitor the download progress and prepares the activity to preview
1667 * or open the file when the download finishes.
1669 * @param file {@link OCFile} to download and preview.
1671 public void startDownloadForPreview(OCFile file
) {
1672 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1673 setSecondFragment(detailFragment
);
1674 mWaitingToPreview
= file
;
1675 requestForDownload();
1676 updateFragmentsVisibility(true
);
1677 updateNavigationElementsInActionBar(file
);
1682 public void cancelTransference(OCFile file
) {
1683 Account account
= getAccount();
1684 if (mDownloaderBinder
!= null
&& mDownloaderBinder
.isDownloading(account
, file
)) {
1685 mDownloaderBinder
.cancel(account
, file
);
1686 onTransferStateChanged(file
, false
, false
);
1688 } else if (mUploaderBinder
!= null
&& mUploaderBinder
.isUploading(account
, file
)) {
1689 mUploaderBinder
.cancel(account
, file
);
1690 if (!file
.fileExists()) {
1691 cleanSecondFragment();
1694 onTransferStateChanged(file
, false
, false
);