1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 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
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.util
.Log
;
52 import android
.view
.View
;
53 import android
.view
.ViewGroup
;
54 import android
.widget
.ArrayAdapter
;
55 import android
.widget
.TextView
;
56 import android
.widget
.Toast
;
58 import com
.actionbarsherlock
.app
.ActionBar
;
59 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
60 import com
.actionbarsherlock
.view
.Menu
;
61 import com
.actionbarsherlock
.view
.MenuInflater
;
62 import com
.actionbarsherlock
.view
.MenuItem
;
63 import com
.actionbarsherlock
.view
.Window
;
64 import com
.owncloud
.android
.MainApp
;
65 import com
.owncloud
.android
.R
;
66 import com
.owncloud
.android
.datamodel
.OCFile
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
81 import com
.owncloud
.android
.operations
.CreateShareOperation
;
82 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
83 import com
.owncloud
.android
.operations
.RenameFileOperation
;
84 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
86 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
87 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
88 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
89 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
92 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
99 import com
.owncloud
.android
.utils
.DisplayUtils
;
100 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
101 import com
.owncloud
.android
.utils
.Log_OC
;
105 * Displays, what files the user has available in his ownCloud.
107 * @author Bartek Przybylski
108 * @author David A. Velasco
111 public class FileDisplayActivity
extends HookActivity
implements
112 FileFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
{
114 private ArrayAdapter
<String
> mDirectories
;
116 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
117 private UploadFinishReceiver mUploadFinishReceiver
;
118 private DownloadFinishReceiver mDownloadFinishReceiver
;
119 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
121 private boolean mDualPane
;
122 private View mLeftFragmentContainer
;
123 private View mRightFragmentContainer
;
125 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
126 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
127 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
129 public static final int DIALOG_SHORT_WAIT
= 0;
130 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
131 private static final int DIALOG_CERT_NOT_SAVED
= 2;
133 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
135 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
136 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
138 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
140 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
143 private OCFile mWaitingToPreview
;
145 private boolean mSyncInProgress
= false
;
147 private String DIALOG_UNTRUSTED_CERT
;
149 private OCFile mWaitingToSend
;
152 protected void onCreate(Bundle savedInstanceState
) {
153 Log_OC
.d(TAG
, "onCreate() start");
154 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
156 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
158 // PIN CODE request ; best location is to decide, let's try this first
159 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
161 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
165 /// grant that FileObserverService is watching favourite files
166 if (savedInstanceState
== null
) {
167 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
168 startService(initObserversIntent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
174 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
175 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
178 mWaitingToPreview
= null
;
179 mSyncInProgress
= 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();
195 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
196 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
197 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
201 Log_OC
.d(TAG
, "onCreate() end");
205 protected void onStart() {
207 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
211 protected void onDestroy() {
216 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
219 protected void onAccountSet(boolean stateWasRecovered
) {
220 super.onAccountSet(stateWasRecovered
);
221 if (getAccount() != null
) {
222 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
223 OCFile file
= getFile();
224 // get parent from path
225 String parentPath
= "";
227 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
228 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
229 // get parent from path
230 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
231 if (getStorageManager().getFileByPath(parentPath
) == null
)
232 file
= null
; // not able to know the directory where the file is uploading
234 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
238 // fall back to root folder
239 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
242 setNavigationListWithFolder(file
);
244 if (!stateWasRecovered
) {
245 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
246 initFragmentsWithFile();
247 if (file
.isFolder()) {
248 startSyncFolderOperation(file
);
252 updateFragmentsVisibility(!file
.isFolder());
253 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
259 private void setNavigationListWithFolder(OCFile file
) {
260 mDirectories
.clear();
261 OCFile fileIt
= file
;
263 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
264 if (fileIt
.isFolder()) {
265 mDirectories
.add(fileIt
.getFileName());
267 // get parent from path
268 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
269 fileIt
= getStorageManager().getFileByPath(parentPath
);
271 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
275 private void createMinFragments() {
276 OCFileListFragment listOfFiles
= new OCFileListFragment();
277 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
278 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
279 transaction
.commit();
282 private void initFragmentsWithFile() {
283 if (getAccount() != null
&& getFile() != null
) {
285 OCFileListFragment listOfFiles
= getListOfFilesFragment();
286 if (listOfFiles
!= null
) {
287 listOfFiles
.listDirectory(getCurrentDir());
289 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
293 OCFile file
= getFile();
294 Fragment secondFragment
= chooseInitialSecondFragment(file
);
295 if (secondFragment
!= null
) {
296 setSecondFragment(secondFragment
);
297 updateFragmentsVisibility(true
);
298 updateNavigationElementsInActionBar(file
);
301 cleanSecondFragment();
305 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
306 if (getAccount() == null
) {
307 Log
.wtf(TAG
, "\t account is NULL");
309 if (getFile() == null
) {
310 Log
.wtf(TAG
, "\t file is NULL");
315 private Fragment
chooseInitialSecondFragment(OCFile file
) {
316 Fragment secondFragment
= null
;
317 if (file
!= null
&& !file
.isFolder()) {
318 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
319 && file
.getLastSyncDateForProperties() > 0 // temporal fix
321 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
322 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
323 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
326 secondFragment
= new FileDetailFragment(file
, getAccount());
329 return secondFragment
;
334 * Replaces the second fragment managed by the activity with the received as
337 * Assumes never will be more than two fragments managed at the same time.
339 * @param fragment New second Fragment to set.
341 private void setSecondFragment(Fragment fragment
) {
342 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
343 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
344 transaction
.commit();
348 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
350 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
351 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
353 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
354 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
357 } else if (existsSecondFragment
) {
358 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
359 mLeftFragmentContainer
.setVisibility(View
.GONE
);
361 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
362 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
366 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
369 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
370 mRightFragmentContainer
.setVisibility(View
.GONE
);
376 private OCFileListFragment
getListOfFilesFragment() {
377 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
378 if (listOfFiles
!= null
) {
379 return (OCFileListFragment
)listOfFiles
;
381 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
385 public FileFragment
getSecondFragment() {
386 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
387 if (second
!= null
) {
388 return (FileFragment
)second
;
393 protected void cleanSecondFragment() {
394 Fragment second
= getSecondFragment();
395 if (second
!= null
) {
396 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
400 updateFragmentsVisibility(false
);
401 updateNavigationElementsInActionBar(null
);
404 protected void refreshListOfFilesFragment() {
405 OCFileListFragment fileListFragment
= getListOfFilesFragment();
406 if (fileListFragment
!= null
) {
407 fileListFragment
.listDirectory();
411 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
412 FileFragment secondFragment
= getSecondFragment();
413 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
414 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
415 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
416 OCFile fileInFragment
= detailsFragment
.getFile();
417 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
418 // the user browsed to other file ; forget the automatic preview
419 mWaitingToPreview
= null
;
421 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
422 // grant that the right panel updates the progress bar
423 detailsFragment
.listenForTransferProgress();
424 detailsFragment
.updateFileDetails(true
, false
);
426 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
427 // update the right panel
428 boolean detailsFragmentChanged
= false
;
431 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
432 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
433 startMediaPreview(mWaitingToPreview
, 0, true
);
434 detailsFragmentChanged
= true
;
436 getFileOperationsHelper().openFile(mWaitingToPreview
);
439 mWaitingToPreview
= null
;
441 if (!detailsFragmentChanged
) {
442 detailsFragment
.updateFileDetails(false
, (success
));
449 public boolean onCreateOptionsMenu(Menu menu
) {
450 MenuInflater inflater
= getSherlock().getMenuInflater();
451 inflater
.inflate(R
.menu
.main_menu
, menu
);
456 public boolean onOptionsItemSelected(MenuItem item
) {
457 boolean retval
= true
;
458 switch (item
.getItemId()) {
459 case R
.id
.action_create_dir
: {
460 CreateFolderDialogFragment dialog
=
461 CreateFolderDialogFragment
.newInstance(getCurrentDir());
462 dialog
.show(getSupportFragmentManager(), "createdirdialog");
465 case R
.id
.action_sync_account
: {
466 startSynchronization();
469 case R
.id
.action_upload
: {
470 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
473 case R
.id
.action_settings
: {
474 Intent settingsIntent
= new Intent(this, Preferences
.class);
475 startActivity(settingsIntent
);
478 case android
.R
.id
.home
: {
479 FileFragment second
= getSecondFragment();
480 OCFile currentDir
= getCurrentDir();
481 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
482 (second
!= null
&& second
.getFile() != null
)) {
489 retval
= super.onOptionsItemSelected(item
);
494 private void startSynchronization() {
495 Log_OC
.e(TAG
, "Got to start sync");
496 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
497 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
498 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
499 Bundle bundle
= new Bundle();
500 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
501 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
502 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
503 ContentResolver
.requestSync(
505 MainApp
.getAuthority(), bundle
);
507 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
508 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
509 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
510 builder
.setExpedited(true
);
511 builder
.setManual(true
);
513 SyncRequest request
= builder
.build();
514 ContentResolver
.requestSync(request
);
520 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
521 if (itemPosition
!= 0) {
522 String targetPath
= "";
523 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
524 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
526 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
527 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
528 if (targetFolder
!= null
) {
529 browseTo(targetFolder
);
532 // the next operation triggers a new call to this method, but it's necessary to
533 // ensure that the name exposed in the action bar is the current directory when the
534 // user selected it in the navigation list
535 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
536 getSupportActionBar().setSelectedNavigationItem(0);
542 * Called, when the user selected something for uploading
544 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
545 super.onActivityResult(requestCode
, resultCode
, data
);
547 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
548 requestSimpleUpload(data
, resultCode
);
550 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
551 requestMultipleUpload(data
, resultCode
);
556 private void requestMultipleUpload(Intent data
, int resultCode
) {
557 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
558 if (filePaths
!= null
) {
559 String
[] remotePaths
= new String
[filePaths
.length
];
560 String remotePathBase
= "";
561 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
562 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
564 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
565 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
566 for (int j
= 0; j
< remotePaths
.length
; j
++) {
567 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
570 Intent i
= new Intent(this, FileUploader
.class);
571 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
572 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
573 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
574 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
575 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
576 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
580 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
581 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
588 private void requestSimpleUpload(Intent data
, int resultCode
) {
589 String filepath
= null
;
591 Uri selectedImageUri
= data
.getData();
593 String filemanagerstring
= selectedImageUri
.getPath();
594 String selectedImagePath
= getPath(selectedImageUri
);
596 if (selectedImagePath
!= null
)
597 filepath
= selectedImagePath
;
599 filepath
= filemanagerstring
;
601 } catch (Exception e
) {
602 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
606 if (filepath
== null
) {
607 Log_OC
.e(TAG
, "Couldnt resolve path to file");
608 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
614 Intent i
= new Intent(this, FileUploader
.class);
615 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
617 String remotepath
= new String();
618 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
619 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
621 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
622 remotepath
+= OCFile
.PATH_SEPARATOR
;
623 remotepath
+= new File(filepath
).getName();
625 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
626 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
627 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
628 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
629 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
634 public void onBackPressed() {
635 OCFileListFragment listOfFiles
= getListOfFilesFragment();
636 if (mDualPane
|| getSecondFragment() == null
) {
637 if (listOfFiles
!= null
) { // should never be null, indeed
638 if (mDirectories
.getCount() <= 1) {
642 int levelsUp
= listOfFiles
.onBrowseUp();
643 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
648 if (listOfFiles
!= null
) { // should never be null, indeed
649 setFile(listOfFiles
.getCurrentFile());
651 cleanSecondFragment();
656 protected void onSaveInstanceState(Bundle outState
) {
657 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
658 Log_OC
.e(TAG
, "onSaveInstanceState() start");
659 super.onSaveInstanceState(outState
);
660 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
661 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
662 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
663 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
665 Log_OC
.d(TAG
, "onSaveInstanceState() end");
671 protected void onResume() {
673 Log_OC
.e(TAG
, "onResume() start");
675 // refresh list of files
676 refreshListOfFilesFragment();
678 // Listen for sync messages
679 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
680 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
681 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
682 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
683 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
684 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
685 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
686 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
688 // Listen for upload messages
689 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
690 mUploadFinishReceiver
= new UploadFinishReceiver();
691 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
693 // Listen for download messages
694 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
695 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
696 mDownloadFinishReceiver
= new DownloadFinishReceiver();
697 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
699 Log_OC
.d(TAG
, "onResume() end");
704 protected void onPause() {
705 Log_OC
.e(TAG
, "onPause() start");
706 if (mSyncBroadcastReceiver
!= null
) {
707 unregisterReceiver(mSyncBroadcastReceiver
);
708 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
709 mSyncBroadcastReceiver
= null
;
711 if (mUploadFinishReceiver
!= null
) {
712 unregisterReceiver(mUploadFinishReceiver
);
713 mUploadFinishReceiver
= null
;
715 if (mDownloadFinishReceiver
!= null
) {
716 unregisterReceiver(mDownloadFinishReceiver
);
717 mDownloadFinishReceiver
= null
;
721 Log_OC
.d(TAG
, "onPause() end");
727 protected Dialog
onCreateDialog(int id
) {
728 Dialog dialog
= null
;
729 AlertDialog
.Builder builder
;
731 case DIALOG_SHORT_WAIT
: {
732 ProgressDialog working_dialog
= new ProgressDialog(this);
733 working_dialog
.setMessage(getResources().getString(
734 R
.string
.wait_a_moment
));
735 working_dialog
.setIndeterminate(true
);
736 working_dialog
.setCancelable(false
);
737 dialog
= working_dialog
;
740 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
743 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
744 getString(R
.string
.actionbar_upload_from_apps
) };
746 builder
= new AlertDialog
.Builder(this);
747 builder
.setTitle(R
.string
.actionbar_upload
);
748 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
749 public void onClick(DialogInterface dialog
, int item
) {
752 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
753 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
754 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
756 // TODO create and handle new fragment
757 // LocalFileListFragment
759 } else if (item
== 1) {
760 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
761 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
762 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
763 ACTION_SELECT_CONTENT_FROM_APPS
);
767 dialog
= builder
.create();
770 case DIALOG_CERT_NOT_SAVED
: {
771 builder
= new AlertDialog
.Builder(this);
772 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
773 builder
.setCancelable(false
);
774 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
776 public void onClick(DialogInterface dialog
, int which
) {
780 dialog
= builder
.create();
792 * Translates a content URI of an image to a physical path
794 * @param uri The URI to resolve
795 * @return The path to the image or null if it could not be found
797 public String
getPath(Uri uri
) {
798 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
799 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
800 if (cursor
!= null
) {
801 int column_index
= cursor
802 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
803 cursor
.moveToFirst();
804 return cursor
.getString(column_index
);
810 * Pushes a directory to the drop down list
811 * @param directory to push
812 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
814 public void pushDirname(OCFile directory
) {
815 if(!directory
.isFolder()){
816 throw new IllegalArgumentException("Only directories may be pushed!");
818 mDirectories
.insert(directory
.getFileName(), 0);
823 * Pops a directory name from the drop down list
824 * @return True, unless the stack is empty
826 public boolean popDirname() {
827 mDirectories
.remove(mDirectories
.getItem(0));
828 return !mDirectories
.isEmpty();
831 // Custom array adapter to override text colors
832 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
834 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
838 public View
getView(int position
, View convertView
, ViewGroup parent
) {
839 View v
= super.getView(position
, convertView
, parent
);
841 ((TextView
) v
).setTextColor(getResources().getColorStateList(
842 android
.R
.color
.white
));
844 fixRoot((TextView
) v
);
848 public View
getDropDownView(int position
, View convertView
,
850 View v
= super.getDropDownView(position
, convertView
, parent
);
852 ((TextView
) v
).setTextColor(getResources().getColorStateList(
853 android
.R
.color
.white
));
855 fixRoot((TextView
) v
);
859 private void fixRoot(TextView v
) {
860 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
861 v
.setText(R
.string
.default_display_name_for_root_folder
);
867 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
870 * {@link BroadcastReceiver} to enable syncing feedback in UI
873 public void onReceive(Context context
, Intent intent
) {
875 String event
= intent
.getAction();
876 Log_OC
.d(TAG
, "Received broadcast " + event
);
877 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
878 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
879 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
880 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
884 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
885 mSyncInProgress
= true
;
888 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
889 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
891 if (currentDir
== null
) {
892 // current folder was removed from the server
893 Toast
.makeText( FileDisplayActivity
.this,
894 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
900 if (currentFile
== null
&& !getFile().isFolder()) {
901 // currently selected file was removed in the server, and now we know it
902 cleanSecondFragment();
903 currentFile
= currentDir
;
906 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
907 OCFileListFragment fileListFragment
= getListOfFilesFragment();
908 if (fileListFragment
!= null
) {
909 fileListFragment
.listDirectory(currentDir
);
912 setFile(currentFile
);
915 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
917 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
919 /// TODO refactor and make common
920 synchResult
!= null
&& !synchResult
.isSuccess() &&
921 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
922 synchResult
.isIdPRedirection() ||
923 (synchResult
.isException() && synchResult
.getException()
924 instanceof AuthenticatorException
))) {
926 OwnCloudClient client
= null
;
928 OwnCloudAccount ocAccount
=
929 new OwnCloudAccount(getAccount(), context
);
930 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
931 removeClientFor(ocAccount
));
932 // TODO get rid of these exceptions
933 } catch (AccountNotFoundException e
) {
935 } catch (AuthenticatorException e
) {
937 } catch (OperationCanceledException e
) {
939 } catch (IOException e
) {
943 if (client
!= null
) {
944 OwnCloudCredentials cred
= client
.getCredentials();
946 AccountManager am
= AccountManager
.get(context
);
947 if (cred
.authTokenExpires()) {
948 am
.invalidateAuthToken(
953 am
.clearPassword(getAccount());
958 requestCredentialsUpdate();
962 removeStickyBroadcast(intent
);
963 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
964 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
970 if (synchResult
!= null
) {
971 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
972 mLastSslUntrustedServerResult
= synchResult
;
975 } catch (RuntimeException e
) {
976 // avoid app crashes after changing the serial id of RemoteOperationResult
977 // in owncloud library with broadcast notifications pending to process
978 removeStickyBroadcast(intent
);
984 * Show a text message on screen view for notifying user if content is
985 * loading or folder is empty
987 private void setBackgroundText() {
988 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
989 if (ocFileListFragment
!= null
) {
990 int message
= R
.string
.file_list_loading
;
991 if (!mSyncInProgress
) {
992 // In case file list is empty
993 message
= R
.string
.file_list_empty
;
995 ocFileListFragment
.setMessageForEmptyList(getString(message
));
997 Log
.e(TAG
, "OCFileListFragment is null");
1002 * Once the file upload has finished -> update view
1004 private class UploadFinishReceiver
extends BroadcastReceiver
{
1006 * Once the file upload has finished -> update view
1007 * @author David A. Velasco
1008 * {@link BroadcastReceiver} to enable upload feedback in UI
1011 public void onReceive(Context context
, Intent intent
) {
1013 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1014 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1015 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1016 OCFile currentDir
= getCurrentDir();
1017 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1018 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1020 if (sameAccount
&& isDescendant
) {
1021 refreshListOfFilesFragment();
1024 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1025 boolean renamedInUpload
= getFile().getRemotePath().
1026 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1027 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1029 FileFragment details
= getSecondFragment();
1030 boolean detailFragmentIsShown
= (details
!= null
&&
1031 details
instanceof FileDetailFragment
);
1033 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1034 if (uploadWasFine
) {
1035 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1037 if (renamedInUpload
) {
1038 String newName
= (new File(uploadedRemotePath
)).getName();
1039 Toast msg
= Toast
.makeText(
1042 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1047 if (uploadWasFine
|| getFile().fileExists()) {
1048 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1050 cleanSecondFragment();
1053 // Force the preview if the file is an image
1054 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1055 startImagePreview(getFile());
1056 } // TODO what about other kind of previews?
1060 if (intent
!= null
) {
1061 removeStickyBroadcast(intent
);
1071 * Class waiting for broadcast events from the {@link FielDownloader} service.
1073 * Updates the UI when a download is started or finished, provided that it is relevant for the
1076 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1078 public void onReceive(Context context
, Intent intent
) {
1080 boolean sameAccount
= isSameAccount(context
, intent
);
1081 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1082 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1084 if (sameAccount
&& isDescendant
) {
1085 refreshListOfFilesFragment();
1086 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1089 if (mWaitingToSend
!= null
) {
1090 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1091 if (mWaitingToSend
.isDown()) {
1092 sendDownloadedFile();
1097 if (intent
!= null
) {
1098 removeStickyBroadcast(intent
);
1103 private boolean isDescendant(String downloadedRemotePath
) {
1104 OCFile currentDir
= getCurrentDir();
1105 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1108 private boolean isSameAccount(Context context
, Intent intent
) {
1109 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1110 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1115 public void browseToRoot() {
1116 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1117 if (listOfFiles
!= null
) { // should never be null, indeed
1118 while (mDirectories
.getCount() > 1) {
1121 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1122 listOfFiles
.listDirectory(root
);
1123 setFile(listOfFiles
.getCurrentFile());
1124 startSyncFolderOperation(root
);
1126 cleanSecondFragment();
1130 public void browseTo(OCFile folder
) {
1131 if (folder
== null
|| !folder
.isFolder()) {
1132 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1134 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1135 if (listOfFiles
!= null
) {
1136 setNavigationListWithFolder(folder
);
1137 listOfFiles
.listDirectory(folder
);
1138 setFile(listOfFiles
.getCurrentFile());
1139 startSyncFolderOperation(folder
);
1141 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1143 cleanSecondFragment();
1150 * Updates action bar and second fragment, if in dual pane mode.
1153 public void onBrowsedDownTo(OCFile directory
) {
1154 pushDirname(directory
);
1155 cleanSecondFragment();
1158 startSyncFolderOperation(directory
);
1163 * Shows the information of the {@link OCFile} received as a
1164 * parameter in the second fragment.
1166 * @param file {@link OCFile} whose details will be shown
1169 public void showDetails(OCFile file
) {
1170 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1171 setSecondFragment(detailFragment
);
1172 updateFragmentsVisibility(true
);
1173 updateNavigationElementsInActionBar(file
);
1181 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1182 ActionBar actionBar
= getSupportActionBar();
1183 if (chosenFile
== null
|| mDualPane
) {
1184 // only list of files - set for browsing through folders
1185 OCFile currentDir
= getCurrentDir();
1186 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1187 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1188 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1190 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1192 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1193 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1196 actionBar
.setDisplayHomeAsUpEnabled(true
);
1197 actionBar
.setDisplayShowTitleEnabled(true
);
1198 actionBar
.setTitle(chosenFile
.getFileName());
1199 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1205 protected ServiceConnection
newTransferenceServiceConnection() {
1206 return new ListServiceConnection();
1209 /** Defines callbacks for service binding, passed to bindService() */
1210 private class ListServiceConnection
implements ServiceConnection
{
1213 public void onServiceConnected(ComponentName component
, IBinder service
) {
1214 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1215 Log_OC
.d(TAG
, "Download service connected");
1216 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1217 if (mWaitingToPreview
!= null
)
1218 if (getStorageManager() != null
) {
1219 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1220 if (!mWaitingToPreview
.isDown()) {
1221 requestForDownload();
1225 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1226 Log_OC
.d(TAG
, "Upload service connected");
1227 mUploaderBinder
= (FileUploaderBinder
) service
;
1231 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1232 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1233 if (listOfFiles
!= null
) {
1234 listOfFiles
.listDirectory();
1236 FileFragment secondFragment
= getSecondFragment();
1237 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1238 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1239 detailFragment
.listenForTransferProgress();
1240 detailFragment
.updateFileDetails(false
, false
);
1245 public void onServiceDisconnected(ComponentName component
) {
1246 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1247 Log_OC
.d(TAG
, "Download service disconnected");
1248 mDownloaderBinder
= null
;
1249 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1250 Log_OC
.d(TAG
, "Upload service disconnected");
1251 mUploaderBinder
= null
;
1259 * Launch an intent to request the PIN code to the user before letting him use the app
1261 private void requestPinCode() {
1262 boolean pinStart
= false
;
1263 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1264 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1266 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1267 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1274 public void onSavedCertificate() {
1275 startSyncFolderOperation(getCurrentDir());
1280 public void onFailedSavingCertificate() {
1281 showDialog(DIALOG_CERT_NOT_SAVED
);
1285 public void onCancelCertificate() {
1290 * Updates the view associated to the activity after the finish of some operation over files
1291 * in the current account.
1293 * @param operation Removal operation performed.
1294 * @param result Result of the removal.
1297 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1298 super.onRemoteOperationFinish(operation
, result
);
1300 if (operation
instanceof RemoveFileOperation
) {
1301 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1303 } else if (operation
instanceof RenameFileOperation
) {
1304 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1306 } else if (operation
instanceof SynchronizeFileOperation
) {
1307 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1309 } else if (operation
instanceof CreateFolderOperation
) {
1310 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1312 } else if (operation
instanceof CreateShareOperation
) {
1313 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1315 } else if (operation
instanceof UnshareLinkOperation
) {
1316 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1323 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1324 if (result
.isSuccess()) {
1325 refreshShowDetails();
1326 refreshListOfFilesFragment();
1331 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1332 if (result
.isSuccess()) {
1333 refreshShowDetails();
1334 refreshListOfFilesFragment();
1336 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1337 cleanSecondFragment();
1338 refreshListOfFilesFragment();
1342 private void refreshShowDetails() {
1343 FileFragment details
= getSecondFragment();
1344 if (details
!= null
) {
1345 OCFile file
= details
.getFile();
1347 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1348 if (details
instanceof PreviewMediaFragment
) {
1349 // Refresh OCFile of the fragment
1350 ((PreviewMediaFragment
) details
).updateFile(file
);
1355 invalidateOptionsMenu();
1360 * Updates the view associated to the activity after the finish of an operation trying to remove a
1363 * @param operation Removal operation performed.
1364 * @param result Result of the removal.
1366 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1367 dismissLoadingDialog();
1369 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1373 if (result
.isSuccess()) {
1374 OCFile removedFile
= operation
.getFile();
1375 FileFragment second
= getSecondFragment();
1376 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1377 if (second
instanceof PreviewMediaFragment
) {
1378 ((PreviewMediaFragment
)second
).stopPreview(true
);
1380 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1381 cleanSecondFragment();
1383 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1384 refreshListOfFilesFragment();
1386 invalidateOptionsMenu();
1388 if (result
.isSslRecoverableException()) {
1389 mLastSslUntrustedServerResult
= result
;
1390 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1397 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1399 * @param operation Creation operation performed.
1400 * @param result Result of the creation.
1402 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1403 if (result
.isSuccess()) {
1404 dismissLoadingDialog();
1405 refreshListOfFilesFragment();
1407 dismissLoadingDialog();
1409 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1410 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1414 } catch (NotFoundException e
) {
1415 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1422 * Updates the view associated to the activity after the finish of an operation trying to rename a
1425 * @param operation Renaming operation performed.
1426 * @param result Result of the renaming.
1428 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1429 dismissLoadingDialog();
1430 OCFile renamedFile
= operation
.getFile();
1431 if (result
.isSuccess()) {
1432 FileFragment details
= getSecondFragment();
1433 if (details
!= null
) {
1434 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1435 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1436 showDetails(renamedFile
);
1438 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1439 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1440 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1441 int position
= ((PreviewMediaFragment
)details
).getPosition();
1442 startMediaPreview(renamedFile
, position
, true
);
1444 getFileOperationsHelper().openFile(renamedFile
);
1449 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1450 refreshListOfFilesFragment();
1454 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1458 if (result
.isSslRecoverableException()) {
1459 mLastSslUntrustedServerResult
= result
;
1460 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1465 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1466 dismissLoadingDialog();
1467 OCFile syncedFile
= operation
.getLocalFile();
1468 if (!result
.isSuccess()) {
1469 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1470 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1471 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1472 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1478 if (operation
.transferWasRequested()) {
1479 onTransferStateChanged(syncedFile
, true
, true
);
1482 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1494 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1495 refreshListOfFilesFragment();
1496 FileFragment details
= getSecondFragment();
1497 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1498 if (downloading
|| uploading
) {
1499 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1501 if (!file
.fileExists()) {
1502 cleanSecondFragment();
1504 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1512 private void requestForDownload() {
1513 Account account
= getAccount();
1514 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1515 Intent i
= new Intent(this, FileDownloader
.class);
1516 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1517 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1523 private OCFile
getCurrentDir() {
1524 OCFile file
= getFile();
1526 if (file
.isFolder()) {
1528 } else if (getStorageManager() != null
) {
1529 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1530 return getStorageManager().getFileByPath(parentPath
);
1536 public void startSyncFolderOperation(OCFile folder
) {
1537 long currentSyncTime
= System
.currentTimeMillis();
1539 mSyncInProgress
= true
;
1541 // perform folder synchronization
1542 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1545 getFileOperationsHelper().isSharedSupported(),
1546 getStorageManager(),
1548 getApplicationContext()
1550 synchFolderOp
.execute(getAccount(), this, null
, null
);
1552 setSupportProgressBarIndeterminateVisibility(true
);
1554 setBackgroundText();
1558 * Show untrusted cert dialog
1560 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1561 // Show a dialog with the certificate info
1562 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1563 FragmentManager fm
= getSupportFragmentManager();
1564 FragmentTransaction ft
= fm
.beginTransaction();
1565 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1568 private void requestForDownload(OCFile file
) {
1569 Account account
= getAccount();
1570 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1571 Intent i
= new Intent(this, FileDownloader
.class);
1572 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1573 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1578 private void sendDownloadedFile(){
1579 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1580 mWaitingToSend
= null
;
1585 * Requests the download of the received {@link OCFile} , updates the UI
1586 * to monitor the download progress and prepares the activity to send the file
1587 * when the download finishes.
1589 * @param file {@link OCFile} to download and preview.
1591 public void startDownloadForSending(OCFile file
) {
1592 mWaitingToSend
= file
;
1593 requestForDownload(mWaitingToSend
);
1594 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1595 updateFragmentsVisibility(hasSecondFragment
);
1599 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1601 * @param file Image {@link OCFile} to show.
1603 public void startImagePreview(OCFile file
) {
1604 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1605 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1606 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1607 startActivity(showDetailsIntent
);
1612 * Stars the preview of an already down media {@link OCFile}.
1614 * @param file Media {@link OCFile} to preview.
1615 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1616 * @param autoplay When 'true', the playback will start without user interactions.
1618 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1619 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1620 setSecondFragment(mediaFragment
);
1621 updateFragmentsVisibility(true
);
1622 updateNavigationElementsInActionBar(file
);
1627 * Requests the download of the received {@link OCFile} , updates the UI
1628 * to monitor the download progress and prepares the activity to preview
1629 * or open the file when the download finishes.
1631 * @param file {@link OCFile} to download and preview.
1633 public void startDownloadForPreview(OCFile file
) {
1634 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1635 setSecondFragment(detailFragment
);
1636 mWaitingToPreview
= file
;
1637 requestForDownload();
1638 updateFragmentsVisibility(true
);
1639 updateNavigationElementsInActionBar(file
);
1644 public void cancelTransference(OCFile file
) {
1645 getFileOperationsHelper().cancelTransference(file
);
1646 if (mWaitingToPreview
!= null
&&
1647 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1648 mWaitingToPreview
= null
;
1650 if (mWaitingToSend
!= null
&&
1651 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1652 mWaitingToSend
= null
;
1654 onTransferStateChanged(file
, false
, false
);