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
.support
.v4
.widget
.SwipeRefreshLayout
;
52 import android
.util
.Log
;
53 import android
.view
.View
;
54 import android
.view
.ViewGroup
;
55 import android
.widget
.ArrayAdapter
;
56 import android
.widget
.TextView
;
57 import android
.widget
.Toast
;
59 import com
.actionbarsherlock
.app
.ActionBar
;
60 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
61 import com
.actionbarsherlock
.view
.Menu
;
62 import com
.actionbarsherlock
.view
.MenuInflater
;
63 import com
.actionbarsherlock
.view
.MenuItem
;
64 import com
.actionbarsherlock
.view
.Window
;
65 import com
.owncloud
.android
.MainApp
;
66 import com
.owncloud
.android
.R
;
67 import com
.owncloud
.android
.datamodel
.OCFile
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
;
69 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
76 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
77 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RenameFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
87 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
88 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
89 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
90 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
93 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
100 import com
.owncloud
.android
.utils
.DisplayUtils
;
101 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
102 import com
.owncloud
.android
.utils
.Log_OC
;
106 * Displays, what files the user has available in his ownCloud.
108 * @author Bartek Przybylski
109 * @author David A. Velasco
112 public class FileDisplayActivity
extends HookActivity
implements
113 FileFragment
.ContainerActivity
, OnNavigationListener
,
114 OnSslUntrustedCertListener
, SwipeRefreshLayout
.OnRefreshListener
{
116 private ArrayAdapter
<String
> mDirectories
;
118 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
119 private UploadFinishReceiver mUploadFinishReceiver
;
120 private DownloadFinishReceiver mDownloadFinishReceiver
;
121 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
123 private boolean mDualPane
;
124 private View mLeftFragmentContainer
;
125 private View mRightFragmentContainer
;
127 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
128 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
129 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
131 public static final int DIALOG_SHORT_WAIT
= 0;
132 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
133 private static final int DIALOG_CERT_NOT_SAVED
= 2;
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
140 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
142 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
143 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
145 private OCFile mWaitingToPreview
;
147 private boolean mSyncInProgress
= false
;
149 private String DIALOG_UNTRUSTED_CERT
;
151 private OCFile mWaitingToSend
;
154 protected void onCreate(Bundle savedInstanceState
) {
155 Log_OC
.d(TAG
, "onCreate() start");
156 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
158 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
160 // PIN CODE request ; best location is to decide, let's try this first
161 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
163 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
167 /// grant that FileObserverService is watching favourite files
168 if (savedInstanceState
== null
) {
169 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
170 startService(initObserversIntent
);
173 /// Load of saved instance state
174 if(savedInstanceState
!= null
) {
175 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
180 mWaitingToPreview
= null
;
181 mSyncInProgress
= false
;
182 mWaitingToSend
= null
;
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
189 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
190 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
191 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
192 if (savedInstanceState
== null
) {
193 createMinFragments();
197 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
198 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
199 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
203 Log_OC
.d(TAG
, "onCreate() end");
207 protected void onStart() {
209 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
213 protected void onDestroy() {
218 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
221 protected void onAccountSet(boolean stateWasRecovered
) {
222 super.onAccountSet(stateWasRecovered
);
223 if (getAccount() != null
) {
224 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
225 OCFile file
= getFile();
226 // get parent from path
227 String parentPath
= "";
229 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
230 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
231 // get parent from path
232 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
233 if (getStorageManager().getFileByPath(parentPath
) == null
)
234 file
= null
; // not able to know the directory where the file is uploading
236 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
240 // fall back to root folder
241 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
244 setNavigationListWithFolder(file
);
246 if (!stateWasRecovered
) {
247 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
248 initFragmentsWithFile();
249 if (file
.isFolder()) {
250 startSyncFolderOperation(file
);
254 updateFragmentsVisibility(!file
.isFolder());
255 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
261 private void setNavigationListWithFolder(OCFile file
) {
262 mDirectories
.clear();
263 OCFile fileIt
= file
;
265 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
266 if (fileIt
.isFolder()) {
267 mDirectories
.add(fileIt
.getFileName());
269 // get parent from path
270 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
271 fileIt
= getStorageManager().getFileByPath(parentPath
);
273 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
277 private void createMinFragments() {
278 OCFileListFragment listOfFiles
= new OCFileListFragment();
279 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
280 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
281 transaction
.commit();
284 private void initFragmentsWithFile() {
285 if (getAccount() != null
&& getFile() != null
) {
287 OCFileListFragment listOfFiles
= getListOfFilesFragment();
288 if (listOfFiles
!= null
) {
289 listOfFiles
.listDirectory(getCurrentDir());
291 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
295 OCFile file
= getFile();
296 Fragment secondFragment
= chooseInitialSecondFragment(file
);
297 if (secondFragment
!= null
) {
298 setSecondFragment(secondFragment
);
299 updateFragmentsVisibility(true
);
300 updateNavigationElementsInActionBar(file
);
303 cleanSecondFragment();
307 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
308 if (getAccount() == null
) {
309 Log
.wtf(TAG
, "\t account is NULL");
311 if (getFile() == null
) {
312 Log
.wtf(TAG
, "\t file is NULL");
317 private Fragment
chooseInitialSecondFragment(OCFile file
) {
318 Fragment secondFragment
= null
;
319 if (file
!= null
&& !file
.isFolder()) {
320 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
321 && file
.getLastSyncDateForProperties() > 0 // temporal fix
323 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
324 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
325 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
328 secondFragment
= new FileDetailFragment(file
, getAccount());
331 return secondFragment
;
336 * Replaces the second fragment managed by the activity with the received as
339 * Assumes never will be more than two fragments managed at the same time.
341 * @param fragment New second Fragment to set.
343 private void setSecondFragment(Fragment fragment
) {
344 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
345 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
346 transaction
.commit();
350 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
352 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
353 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
355 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
356 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
359 } else if (existsSecondFragment
) {
360 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
361 mLeftFragmentContainer
.setVisibility(View
.GONE
);
363 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
368 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
371 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
372 mRightFragmentContainer
.setVisibility(View
.GONE
);
378 private OCFileListFragment
getListOfFilesFragment() {
379 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
380 if (listOfFiles
!= null
) {
381 return (OCFileListFragment
)listOfFiles
;
383 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
387 public FileFragment
getSecondFragment() {
388 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
389 if (second
!= null
) {
390 return (FileFragment
)second
;
395 protected void cleanSecondFragment() {
396 Fragment second
= getSecondFragment();
397 if (second
!= null
) {
398 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
402 updateFragmentsVisibility(false
);
403 updateNavigationElementsInActionBar(null
);
406 protected void refreshListOfFilesFragment() {
407 OCFileListFragment fileListFragment
= getListOfFilesFragment();
408 if (fileListFragment
!= null
) {
409 fileListFragment
.listDirectory();
413 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
414 FileFragment secondFragment
= getSecondFragment();
415 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
416 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
417 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
418 OCFile fileInFragment
= detailsFragment
.getFile();
419 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
420 // the user browsed to other file ; forget the automatic preview
421 mWaitingToPreview
= null
;
423 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
424 // grant that the right panel updates the progress bar
425 detailsFragment
.listenForTransferProgress();
426 detailsFragment
.updateFileDetails(true
, false
);
428 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
429 // update the right panel
430 boolean detailsFragmentChanged
= false
;
433 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
434 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
435 startMediaPreview(mWaitingToPreview
, 0, true
);
436 detailsFragmentChanged
= true
;
438 getFileOperationsHelper().openFile(mWaitingToPreview
);
441 mWaitingToPreview
= null
;
443 if (!detailsFragmentChanged
) {
444 detailsFragment
.updateFileDetails(false
, (success
));
451 public boolean onCreateOptionsMenu(Menu menu
) {
452 MenuInflater inflater
= getSherlock().getMenuInflater();
453 inflater
.inflate(R
.menu
.main_menu
, menu
);
458 public boolean onOptionsItemSelected(MenuItem item
) {
459 boolean retval
= true
;
460 switch (item
.getItemId()) {
461 case R
.id
.action_create_dir
: {
462 CreateFolderDialogFragment dialog
=
463 CreateFolderDialogFragment
.newInstance(getCurrentDir());
464 dialog
.show(getSupportFragmentManager(), "createdirdialog");
467 case R
.id
.action_sync_account
: {
468 startSynchronization();
471 case R
.id
.action_upload
: {
472 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
475 case R
.id
.action_settings
: {
476 Intent settingsIntent
= new Intent(this, Preferences
.class);
477 startActivity(settingsIntent
);
480 case android
.R
.id
.home
: {
481 FileFragment second
= getSecondFragment();
482 OCFile currentDir
= getCurrentDir();
483 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
484 (second
!= null
&& second
.getFile() != null
)) {
491 retval
= super.onOptionsItemSelected(item
);
496 private void startSynchronization() {
497 Log_OC
.e(TAG
, "Got to start sync");
498 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
499 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
500 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
501 Bundle bundle
= new Bundle();
502 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
503 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
504 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
505 ContentResolver
.requestSync(
507 MainApp
.getAuthority(), bundle
);
509 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
510 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
511 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
512 builder
.setExpedited(true
);
513 builder
.setManual(true
);
515 SyncRequest request
= builder
.build();
516 ContentResolver
.requestSync(request
);
522 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
523 if (itemPosition
!= 0) {
524 String targetPath
= "";
525 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
526 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
528 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
529 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
530 if (targetFolder
!= null
) {
531 browseTo(targetFolder
);
534 // the next operation triggers a new call to this method, but it's necessary to
535 // ensure that the name exposed in the action bar is the current directory when the
536 // user selected it in the navigation list
537 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
538 getSupportActionBar().setSelectedNavigationItem(0);
544 * Called, when the user selected something for uploading
546 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
547 super.onActivityResult(requestCode
, resultCode
, data
);
549 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
550 requestSimpleUpload(data
, resultCode
);
552 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
553 requestMultipleUpload(data
, resultCode
);
558 private void requestMultipleUpload(Intent data
, int resultCode
) {
559 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
560 if (filePaths
!= null
) {
561 String
[] remotePaths
= new String
[filePaths
.length
];
562 String remotePathBase
= "";
563 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
564 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
566 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
567 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
568 for (int j
= 0; j
< remotePaths
.length
; j
++) {
569 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
572 Intent i
= new Intent(this, FileUploader
.class);
573 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
574 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
575 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
576 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
577 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
578 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
582 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
583 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
590 private void requestSimpleUpload(Intent data
, int resultCode
) {
591 String filepath
= null
;
593 Uri selectedImageUri
= data
.getData();
595 String filemanagerstring
= selectedImageUri
.getPath();
596 String selectedImagePath
= getPath(selectedImageUri
);
598 if (selectedImagePath
!= null
)
599 filepath
= selectedImagePath
;
601 filepath
= filemanagerstring
;
603 } catch (Exception e
) {
604 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
608 if (filepath
== null
) {
609 Log_OC
.e(TAG
, "Couldnt resolve path to file");
610 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
616 Intent i
= new Intent(this, FileUploader
.class);
617 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
619 String remotepath
= new String();
620 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
621 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
623 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
624 remotepath
+= OCFile
.PATH_SEPARATOR
;
625 remotepath
+= new File(filepath
).getName();
627 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
628 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
629 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
630 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
631 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
636 public void onBackPressed() {
637 OCFileListFragment listOfFiles
= getListOfFilesFragment();
638 if (mDualPane
|| getSecondFragment() == null
) {
639 if (listOfFiles
!= null
) { // should never be null, indeed
640 if (mDirectories
.getCount() <= 1) {
644 int levelsUp
= listOfFiles
.onBrowseUp();
645 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
650 if (listOfFiles
!= null
) { // should never be null, indeed
651 setFile(listOfFiles
.getCurrentFile());
653 cleanSecondFragment();
658 protected void onSaveInstanceState(Bundle outState
) {
659 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
660 Log_OC
.e(TAG
, "onSaveInstanceState() start");
661 super.onSaveInstanceState(outState
);
662 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
663 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
664 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
665 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
667 Log_OC
.d(TAG
, "onSaveInstanceState() end");
673 protected void onResume() {
675 Log_OC
.e(TAG
, "onResume() start");
677 // refresh list of files
678 refreshListOfFilesFragment();
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_CONTENTS_SYNCED
);
684 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
685 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
686 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
687 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
688 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
690 // Listen for upload messages
691 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
692 mUploadFinishReceiver
= new UploadFinishReceiver();
693 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
695 // Listen for download messages
696 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
697 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
698 mDownloadFinishReceiver
= new DownloadFinishReceiver();
699 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
701 Log_OC
.d(TAG
, "onResume() end");
706 protected void onPause() {
707 Log_OC
.e(TAG
, "onPause() start");
708 if (mSyncBroadcastReceiver
!= null
) {
709 unregisterReceiver(mSyncBroadcastReceiver
);
710 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
711 mSyncBroadcastReceiver
= null
;
713 if (mUploadFinishReceiver
!= null
) {
714 unregisterReceiver(mUploadFinishReceiver
);
715 mUploadFinishReceiver
= null
;
717 if (mDownloadFinishReceiver
!= null
) {
718 unregisterReceiver(mDownloadFinishReceiver
);
719 mDownloadFinishReceiver
= null
;
723 Log_OC
.d(TAG
, "onPause() end");
729 protected Dialog
onCreateDialog(int id
) {
730 Dialog dialog
= null
;
731 AlertDialog
.Builder builder
;
733 case DIALOG_SHORT_WAIT
: {
734 ProgressDialog working_dialog
= new ProgressDialog(this);
735 working_dialog
.setMessage(getResources().getString(
736 R
.string
.wait_a_moment
));
737 working_dialog
.setIndeterminate(true
);
738 working_dialog
.setCancelable(false
);
739 dialog
= working_dialog
;
742 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
745 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
746 getString(R
.string
.actionbar_upload_from_apps
) };
748 builder
= new AlertDialog
.Builder(this);
749 builder
.setTitle(R
.string
.actionbar_upload
);
750 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
751 public void onClick(DialogInterface dialog
, int item
) {
754 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
755 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
756 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
758 // TODO create and handle new fragment
759 // LocalFileListFragment
761 } else if (item
== 1) {
762 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
763 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
764 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
765 ACTION_SELECT_CONTENT_FROM_APPS
);
769 dialog
= builder
.create();
772 case DIALOG_CERT_NOT_SAVED
: {
773 builder
= new AlertDialog
.Builder(this);
774 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
775 builder
.setCancelable(false
);
776 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
778 public void onClick(DialogInterface dialog
, int which
) {
782 dialog
= builder
.create();
794 * Translates a content URI of an image to a physical path
796 * @param uri The URI to resolve
797 * @return The path to the image or null if it could not be found
799 public String
getPath(Uri uri
) {
800 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
801 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
802 if (cursor
!= null
) {
803 int column_index
= cursor
804 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
805 cursor
.moveToFirst();
806 return cursor
.getString(column_index
);
812 * Pushes a directory to the drop down list
813 * @param directory to push
814 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
816 public void pushDirname(OCFile directory
) {
817 if(!directory
.isFolder()){
818 throw new IllegalArgumentException("Only directories may be pushed!");
820 mDirectories
.insert(directory
.getFileName(), 0);
825 * Pops a directory name from the drop down list
826 * @return True, unless the stack is empty
828 public boolean popDirname() {
829 mDirectories
.remove(mDirectories
.getItem(0));
830 return !mDirectories
.isEmpty();
833 // Custom array adapter to override text colors
834 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
836 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
840 public View
getView(int position
, View convertView
, ViewGroup parent
) {
841 View v
= super.getView(position
, convertView
, parent
);
843 ((TextView
) v
).setTextColor(getResources().getColorStateList(
844 android
.R
.color
.white
));
846 fixRoot((TextView
) v
);
850 public View
getDropDownView(int position
, View convertView
,
852 View v
= super.getDropDownView(position
, convertView
, parent
);
854 ((TextView
) v
).setTextColor(getResources().getColorStateList(
855 android
.R
.color
.white
));
857 fixRoot((TextView
) v
);
861 private void fixRoot(TextView v
) {
862 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
863 v
.setText(R
.string
.default_display_name_for_root_folder
);
869 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
872 * {@link BroadcastReceiver} to enable syncing feedback in UI
875 public void onReceive(Context context
, Intent intent
) {
877 String event
= intent
.getAction();
878 Log_OC
.d(TAG
, "Received broadcast " + event
);
879 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
880 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
881 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
882 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
886 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
887 mSyncInProgress
= true
;
890 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
891 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
893 if (currentDir
== null
) {
894 // current folder was removed from the server
895 Toast
.makeText( FileDisplayActivity
.this,
896 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
902 if (currentFile
== null
&& !getFile().isFolder()) {
903 // currently selected file was removed in the server, and now we know it
904 cleanSecondFragment();
905 currentFile
= currentDir
;
908 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
909 OCFileListFragment fileListFragment
= getListOfFilesFragment();
910 if (fileListFragment
!= null
) {
911 fileListFragment
.listDirectory(currentDir
);
914 setFile(currentFile
);
917 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
919 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
921 /// TODO refactor and make common
922 synchResult
!= null
&& !synchResult
.isSuccess() &&
923 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
924 synchResult
.isIdPRedirection() ||
925 (synchResult
.isException() && synchResult
.getException()
926 instanceof AuthenticatorException
))) {
928 OwnCloudClient client
= null
;
930 OwnCloudAccount ocAccount
=
931 new OwnCloudAccount(getAccount(), context
);
932 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
933 removeClientFor(ocAccount
));
934 // TODO get rid of these exceptions
935 } catch (AccountNotFoundException e
) {
937 } catch (AuthenticatorException e
) {
939 } catch (OperationCanceledException e
) {
941 } catch (IOException e
) {
945 if (client
!= null
) {
946 OwnCloudCredentials cred
= client
.getCredentials();
948 AccountManager am
= AccountManager
.get(context
);
949 if (cred
.authTokenExpires()) {
950 am
.invalidateAuthToken(
955 am
.clearPassword(getAccount());
960 requestCredentialsUpdate();
964 removeStickyBroadcast(intent
);
965 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
966 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
972 if (synchResult
!= null
) {
973 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
974 mLastSslUntrustedServerResult
= synchResult
;
977 } catch (RuntimeException e
) {
978 // avoid app crashes after changing the serial id of RemoteOperationResult
979 // in owncloud library with broadcast notifications pending to process
980 removeStickyBroadcast(intent
);
986 * Show a text message on screen view for notifying user if content is
987 * loading or folder is empty
989 private void setBackgroundText() {
990 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
991 if (ocFileListFragment
!= null
) {
992 int message
= R
.string
.file_list_loading
;
993 if (!mSyncInProgress
) {
994 // In case file list is empty
995 message
= R
.string
.file_list_empty
;
997 ocFileListFragment
.setMessageForEmptyList(getString(message
));
999 Log
.e(TAG
, "OCFileListFragment is null");
1004 * Once the file upload has finished -> update view
1006 private class UploadFinishReceiver
extends BroadcastReceiver
{
1008 * Once the file upload has finished -> update view
1009 * @author David A. Velasco
1010 * {@link BroadcastReceiver} to enable upload feedback in UI
1013 public void onReceive(Context context
, Intent intent
) {
1015 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1016 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1017 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1018 OCFile currentDir
= getCurrentDir();
1019 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1020 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1022 if (sameAccount
&& isDescendant
) {
1023 refreshListOfFilesFragment();
1026 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1027 boolean renamedInUpload
= getFile().getRemotePath().
1028 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1029 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1031 FileFragment details
= getSecondFragment();
1032 boolean detailFragmentIsShown
= (details
!= null
&&
1033 details
instanceof FileDetailFragment
);
1035 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1036 if (uploadWasFine
) {
1037 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1039 if (renamedInUpload
) {
1040 String newName
= (new File(uploadedRemotePath
)).getName();
1041 Toast msg
= Toast
.makeText(
1044 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1049 if (uploadWasFine
|| getFile().fileExists()) {
1050 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1052 cleanSecondFragment();
1055 // Force the preview if the file is an image
1056 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1057 startImagePreview(getFile());
1058 } // TODO what about other kind of previews?
1062 if (intent
!= null
) {
1063 removeStickyBroadcast(intent
);
1073 * Class waiting for broadcast events from the {@link FielDownloader} service.
1075 * Updates the UI when a download is started or finished, provided that it is relevant for the
1078 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1080 public void onReceive(Context context
, Intent intent
) {
1082 boolean sameAccount
= isSameAccount(context
, intent
);
1083 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1084 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1086 if (sameAccount
&& isDescendant
) {
1087 refreshListOfFilesFragment();
1088 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1091 if (mWaitingToSend
!= null
) {
1092 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1093 if (mWaitingToSend
.isDown()) {
1094 sendDownloadedFile();
1099 if (intent
!= null
) {
1100 removeStickyBroadcast(intent
);
1105 private boolean isDescendant(String downloadedRemotePath
) {
1106 OCFile currentDir
= getCurrentDir();
1107 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1110 private boolean isSameAccount(Context context
, Intent intent
) {
1111 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1112 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1117 public void browseToRoot() {
1118 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1119 if (listOfFiles
!= null
) { // should never be null, indeed
1120 while (mDirectories
.getCount() > 1) {
1123 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1124 listOfFiles
.listDirectory(root
);
1125 setFile(listOfFiles
.getCurrentFile());
1126 startSyncFolderOperation(root
);
1128 cleanSecondFragment();
1132 public void browseTo(OCFile folder
) {
1133 if (folder
== null
|| !folder
.isFolder()) {
1134 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1136 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1137 if (listOfFiles
!= null
) {
1138 setNavigationListWithFolder(folder
);
1139 listOfFiles
.listDirectory(folder
);
1140 setFile(listOfFiles
.getCurrentFile());
1141 startSyncFolderOperation(folder
);
1143 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1145 cleanSecondFragment();
1152 * Updates action bar and second fragment, if in dual pane mode.
1155 public void onBrowsedDownTo(OCFile directory
) {
1156 pushDirname(directory
);
1157 cleanSecondFragment();
1160 startSyncFolderOperation(directory
);
1165 * Shows the information of the {@link OCFile} received as a
1166 * parameter in the second fragment.
1168 * @param file {@link OCFile} whose details will be shown
1171 public void showDetails(OCFile file
) {
1172 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1173 setSecondFragment(detailFragment
);
1174 updateFragmentsVisibility(true
);
1175 updateNavigationElementsInActionBar(file
);
1183 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1184 ActionBar actionBar
= getSupportActionBar();
1185 if (chosenFile
== null
|| mDualPane
) {
1186 // only list of files - set for browsing through folders
1187 OCFile currentDir
= getCurrentDir();
1188 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1189 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1190 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1192 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1194 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1195 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1198 actionBar
.setDisplayHomeAsUpEnabled(true
);
1199 actionBar
.setDisplayShowTitleEnabled(true
);
1200 actionBar
.setTitle(chosenFile
.getFileName());
1201 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1207 protected ServiceConnection
newTransferenceServiceConnection() {
1208 return new ListServiceConnection();
1211 /** Defines callbacks for service binding, passed to bindService() */
1212 private class ListServiceConnection
implements ServiceConnection
{
1215 public void onServiceConnected(ComponentName component
, IBinder service
) {
1216 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1217 Log_OC
.d(TAG
, "Download service connected");
1218 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1219 if (mWaitingToPreview
!= null
)
1220 if (getStorageManager() != null
) {
1221 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1222 if (!mWaitingToPreview
.isDown()) {
1223 requestForDownload();
1227 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1228 Log_OC
.d(TAG
, "Upload service connected");
1229 mUploaderBinder
= (FileUploaderBinder
) service
;
1233 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1234 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1235 if (listOfFiles
!= null
) {
1236 listOfFiles
.listDirectory();
1238 FileFragment secondFragment
= getSecondFragment();
1239 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1240 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1241 detailFragment
.listenForTransferProgress();
1242 detailFragment
.updateFileDetails(false
, false
);
1247 public void onServiceDisconnected(ComponentName component
) {
1248 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1249 Log_OC
.d(TAG
, "Download service disconnected");
1250 mDownloaderBinder
= null
;
1251 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1252 Log_OC
.d(TAG
, "Upload service disconnected");
1253 mUploaderBinder
= null
;
1261 * Launch an intent to request the PIN code to the user before letting him use the app
1263 private void requestPinCode() {
1264 boolean pinStart
= false
;
1265 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1266 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1268 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1269 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1276 public void onSavedCertificate() {
1277 startSyncFolderOperation(getCurrentDir());
1282 public void onFailedSavingCertificate() {
1283 showDialog(DIALOG_CERT_NOT_SAVED
);
1287 public void onCancelCertificate() {
1292 * Updates the view associated to the activity after the finish of some operation over files
1293 * in the current account.
1295 * @param operation Removal operation performed.
1296 * @param result Result of the removal.
1299 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1300 super.onRemoteOperationFinish(operation
, result
);
1302 if (operation
instanceof RemoveFileOperation
) {
1303 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1305 } else if (operation
instanceof RenameFileOperation
) {
1306 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1308 } else if (operation
instanceof SynchronizeFileOperation
) {
1309 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1311 } else if (operation
instanceof CreateFolderOperation
) {
1312 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1314 } else if (operation
instanceof CreateShareOperation
) {
1315 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1317 } else if (operation
instanceof UnshareLinkOperation
) {
1318 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1325 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1326 if (result
.isSuccess()) {
1327 refreshShowDetails();
1328 refreshListOfFilesFragment();
1333 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1334 if (result
.isSuccess()) {
1335 refreshShowDetails();
1336 refreshListOfFilesFragment();
1338 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1339 cleanSecondFragment();
1340 refreshListOfFilesFragment();
1344 private void refreshShowDetails() {
1345 FileFragment details
= getSecondFragment();
1346 if (details
!= null
) {
1347 OCFile file
= details
.getFile();
1349 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1350 if (details
instanceof PreviewMediaFragment
) {
1351 // Refresh OCFile of the fragment
1352 ((PreviewMediaFragment
) details
).updateFile(file
);
1357 invalidateOptionsMenu();
1362 * Updates the view associated to the activity after the finish of an operation trying to remove a
1365 * @param operation Removal operation performed.
1366 * @param result Result of the removal.
1368 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1369 dismissLoadingDialog();
1371 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1375 if (result
.isSuccess()) {
1376 OCFile removedFile
= operation
.getFile();
1377 FileFragment second
= getSecondFragment();
1378 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1379 if (second
instanceof PreviewMediaFragment
) {
1380 ((PreviewMediaFragment
)second
).stopPreview(true
);
1382 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1383 cleanSecondFragment();
1385 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1386 refreshListOfFilesFragment();
1388 invalidateOptionsMenu();
1390 if (result
.isSslRecoverableException()) {
1391 mLastSslUntrustedServerResult
= result
;
1392 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1399 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1401 * @param operation Creation operation performed.
1402 * @param result Result of the creation.
1404 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1405 if (result
.isSuccess()) {
1406 dismissLoadingDialog();
1407 refreshListOfFilesFragment();
1409 dismissLoadingDialog();
1411 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1412 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1416 } catch (NotFoundException e
) {
1417 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1424 * Updates the view associated to the activity after the finish of an operation trying to rename a
1427 * @param operation Renaming operation performed.
1428 * @param result Result of the renaming.
1430 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1431 dismissLoadingDialog();
1432 OCFile renamedFile
= operation
.getFile();
1433 if (result
.isSuccess()) {
1434 FileFragment details
= getSecondFragment();
1435 if (details
!= null
) {
1436 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1437 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1438 showDetails(renamedFile
);
1440 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1441 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1442 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1443 int position
= ((PreviewMediaFragment
)details
).getPosition();
1444 startMediaPreview(renamedFile
, position
, true
);
1446 getFileOperationsHelper().openFile(renamedFile
);
1451 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1452 refreshListOfFilesFragment();
1456 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1460 if (result
.isSslRecoverableException()) {
1461 mLastSslUntrustedServerResult
= result
;
1462 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1467 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1468 dismissLoadingDialog();
1469 OCFile syncedFile
= operation
.getLocalFile();
1470 if (!result
.isSuccess()) {
1471 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1472 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1473 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1474 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1480 if (operation
.transferWasRequested()) {
1481 onTransferStateChanged(syncedFile
, true
, true
);
1484 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1496 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1497 refreshListOfFilesFragment();
1498 FileFragment details
= getSecondFragment();
1499 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1500 if (downloading
|| uploading
) {
1501 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1503 if (!file
.fileExists()) {
1504 cleanSecondFragment();
1506 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1514 private void requestForDownload() {
1515 Account account
= getAccount();
1516 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1517 Intent i
= new Intent(this, FileDownloader
.class);
1518 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1519 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1525 private OCFile
getCurrentDir() {
1526 OCFile file
= getFile();
1528 if (file
.isFolder()) {
1530 } else if (getStorageManager() != null
) {
1531 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1532 return getStorageManager().getFileByPath(parentPath
);
1538 public void startSyncFolderOperation(OCFile folder
) {
1539 long currentSyncTime
= System
.currentTimeMillis();
1541 mSyncInProgress
= true
;
1543 // perform folder synchronization
1544 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1547 getFileOperationsHelper().isSharedSupported(),
1548 getStorageManager(),
1550 getApplicationContext()
1552 synchFolderOp
.execute(getAccount(), this, null
, null
);
1554 setSupportProgressBarIndeterminateVisibility(true
);
1556 setBackgroundText();
1560 * Show untrusted cert dialog
1562 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1563 // Show a dialog with the certificate info
1564 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1565 FragmentManager fm
= getSupportFragmentManager();
1566 FragmentTransaction ft
= fm
.beginTransaction();
1567 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1570 private void requestForDownload(OCFile file
) {
1571 Account account
= getAccount();
1572 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1573 Intent i
= new Intent(this, FileDownloader
.class);
1574 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1575 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1580 private void sendDownloadedFile(){
1581 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1582 mWaitingToSend
= null
;
1587 * Requests the download of the received {@link OCFile} , updates the UI
1588 * to monitor the download progress and prepares the activity to send the file
1589 * when the download finishes.
1591 * @param file {@link OCFile} to download and preview.
1593 public void startDownloadForSending(OCFile file
) {
1594 mWaitingToSend
= file
;
1595 requestForDownload(mWaitingToSend
);
1596 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1597 updateFragmentsVisibility(hasSecondFragment
);
1601 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1603 * @param file Image {@link OCFile} to show.
1605 public void startImagePreview(OCFile file
) {
1606 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1607 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1608 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1609 startActivity(showDetailsIntent
);
1614 * Stars the preview of an already down media {@link OCFile}.
1616 * @param file Media {@link OCFile} to preview.
1617 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1618 * @param autoplay When 'true', the playback will start without user interactions.
1620 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1621 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1622 setSecondFragment(mediaFragment
);
1623 updateFragmentsVisibility(true
);
1624 updateNavigationElementsInActionBar(file
);
1629 * Requests the download of the received {@link OCFile} , updates the UI
1630 * to monitor the download progress and prepares the activity to preview
1631 * or open the file when the download finishes.
1633 * @param file {@link OCFile} to download and preview.
1635 public void startDownloadForPreview(OCFile file
) {
1636 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1637 setSecondFragment(detailFragment
);
1638 mWaitingToPreview
= file
;
1639 requestForDownload();
1640 updateFragmentsVisibility(true
);
1641 updateNavigationElementsInActionBar(file
);
1646 public void cancelTransference(OCFile file
) {
1647 getFileOperationsHelper().cancelTransference(file
);
1648 if (mWaitingToPreview
!= null
&&
1649 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1650 mWaitingToPreview
= null
;
1652 if (mWaitingToSend
!= null
&&
1653 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1654 mWaitingToSend
= null
;
1656 onTransferStateChanged(file
, false
, false
);
1660 public void onRefresh() {
1661 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1662 if (listOfFiles
!= null
) {
1663 OCFile folder
= listOfFiles
.getCurrentFile();
1664 if (folder
!= null
) {
1665 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1666 listDirectory(mFile);*/
1667 startSyncFolderOperation(folder
);