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;
139 public static final int ACTION_MOVE_FILES
= 3;
141 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
143 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
144 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
146 private OCFile mWaitingToPreview
;
148 private boolean mSyncInProgress
= false
;
150 private String DIALOG_UNTRUSTED_CERT
;
152 private OCFile mWaitingToSend
;
155 protected void onCreate(Bundle savedInstanceState
) {
156 Log_OC
.d(TAG
, "onCreate() start");
157 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
159 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
161 // PIN CODE request ; best location is to decide, let's try this first
162 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
164 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
168 /// grant that FileObserverService is watching favourite files
169 if (savedInstanceState
== null
) {
170 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
171 startService(initObserversIntent
);
174 /// Load of saved instance state
175 if(savedInstanceState
!= null
) {
176 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
177 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
178 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
181 mWaitingToPreview
= null
;
182 mSyncInProgress
= false
;
183 mWaitingToSend
= null
;
188 // Inflate and set the layout view
189 setContentView(R
.layout
.files
);
190 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
191 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
192 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
193 if (savedInstanceState
== null
) {
194 createMinFragments();
198 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
199 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
200 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
204 Log_OC
.d(TAG
, "onCreate() end");
208 protected void onStart() {
210 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
214 protected void onDestroy() {
219 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
222 protected void onAccountSet(boolean stateWasRecovered
) {
223 super.onAccountSet(stateWasRecovered
);
224 if (getAccount() != null
) {
225 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
226 OCFile file
= getFile();
227 // get parent from path
228 String parentPath
= "";
230 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
231 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
232 // get parent from path
233 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
234 if (getStorageManager().getFileByPath(parentPath
) == null
)
235 file
= null
; // not able to know the directory where the file is uploading
237 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
241 // fall back to root folder
242 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
245 setNavigationListWithFolder(file
);
247 if (!stateWasRecovered
) {
248 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
249 initFragmentsWithFile();
250 if (file
.isFolder()) {
251 startSyncFolderOperation(file
);
255 updateFragmentsVisibility(!file
.isFolder());
256 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
262 private void setNavigationListWithFolder(OCFile file
) {
263 mDirectories
.clear();
264 OCFile fileIt
= file
;
266 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
267 if (fileIt
.isFolder()) {
268 mDirectories
.add(fileIt
.getFileName());
270 // get parent from path
271 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
272 fileIt
= getStorageManager().getFileByPath(parentPath
);
274 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
278 private void createMinFragments() {
279 OCFileListFragment listOfFiles
= new OCFileListFragment();
280 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
281 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
282 transaction
.commit();
285 private void initFragmentsWithFile() {
286 if (getAccount() != null
&& getFile() != null
) {
288 OCFileListFragment listOfFiles
= getListOfFilesFragment();
289 if (listOfFiles
!= null
) {
290 listOfFiles
.listDirectory(getCurrentDir());
292 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
296 OCFile file
= getFile();
297 Fragment secondFragment
= chooseInitialSecondFragment(file
);
298 if (secondFragment
!= null
) {
299 setSecondFragment(secondFragment
);
300 updateFragmentsVisibility(true
);
301 updateNavigationElementsInActionBar(file
);
304 cleanSecondFragment();
308 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
309 if (getAccount() == null
) {
310 Log
.wtf(TAG
, "\t account is NULL");
312 if (getFile() == null
) {
313 Log
.wtf(TAG
, "\t file is NULL");
318 private Fragment
chooseInitialSecondFragment(OCFile file
) {
319 Fragment secondFragment
= null
;
320 if (file
!= null
&& !file
.isFolder()) {
321 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
322 && file
.getLastSyncDateForProperties() > 0 // temporal fix
324 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
325 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
326 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
329 secondFragment
= new FileDetailFragment(file
, getAccount());
332 return secondFragment
;
337 * Replaces the second fragment managed by the activity with the received as
340 * Assumes never will be more than two fragments managed at the same time.
342 * @param fragment New second Fragment to set.
344 private void setSecondFragment(Fragment fragment
) {
345 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
346 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
347 transaction
.commit();
351 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
353 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
354 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
356 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
357 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
360 } else if (existsSecondFragment
) {
361 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
362 mLeftFragmentContainer
.setVisibility(View
.GONE
);
364 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
369 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
372 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
373 mRightFragmentContainer
.setVisibility(View
.GONE
);
379 private OCFileListFragment
getListOfFilesFragment() {
380 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
381 if (listOfFiles
!= null
) {
382 return (OCFileListFragment
)listOfFiles
;
384 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
388 public FileFragment
getSecondFragment() {
389 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
390 if (second
!= null
) {
391 return (FileFragment
)second
;
396 protected void cleanSecondFragment() {
397 Fragment second
= getSecondFragment();
398 if (second
!= null
) {
399 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
403 updateFragmentsVisibility(false
);
404 updateNavigationElementsInActionBar(null
);
407 protected void refreshListOfFilesFragment() {
408 OCFileListFragment fileListFragment
= getListOfFilesFragment();
409 if (fileListFragment
!= null
) {
410 fileListFragment
.listDirectory();
414 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
415 FileFragment secondFragment
= getSecondFragment();
416 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
417 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
418 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
419 OCFile fileInFragment
= detailsFragment
.getFile();
420 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
421 // the user browsed to other file ; forget the automatic preview
422 mWaitingToPreview
= null
;
424 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
425 // grant that the right panel updates the progress bar
426 detailsFragment
.listenForTransferProgress();
427 detailsFragment
.updateFileDetails(true
, false
);
429 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
430 // update the right panel
431 boolean detailsFragmentChanged
= false
;
434 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
435 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
436 startMediaPreview(mWaitingToPreview
, 0, true
);
437 detailsFragmentChanged
= true
;
439 getFileOperationsHelper().openFile(mWaitingToPreview
);
442 mWaitingToPreview
= null
;
444 if (!detailsFragmentChanged
) {
445 detailsFragment
.updateFileDetails(false
, (success
));
452 public boolean onCreateOptionsMenu(Menu menu
) {
453 MenuInflater inflater
= getSherlock().getMenuInflater();
454 inflater
.inflate(R
.menu
.main_menu
, menu
);
459 public boolean onOptionsItemSelected(MenuItem item
) {
460 boolean retval
= true
;
461 switch (item
.getItemId()) {
462 case R
.id
.action_create_dir
: {
463 CreateFolderDialogFragment dialog
=
464 CreateFolderDialogFragment
.newInstance(getCurrentDir());
465 dialog
.show(getSupportFragmentManager(), "createdirdialog");
468 case R
.id
.action_sync_account
: {
469 startSynchronization();
472 case R
.id
.action_upload
: {
473 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
476 case R
.id
.action_settings
: {
477 Intent settingsIntent
= new Intent(this, Preferences
.class);
478 startActivity(settingsIntent
);
481 case android
.R
.id
.home
: {
482 FileFragment second
= getSecondFragment();
483 OCFile currentDir
= getCurrentDir();
484 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
485 (second
!= null
&& second
.getFile() != null
)) {
492 retval
= super.onOptionsItemSelected(item
);
497 private void startSynchronization() {
498 Log_OC
.e(TAG
, "Got to start sync");
499 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
500 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
501 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
502 Bundle bundle
= new Bundle();
503 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
504 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
505 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
506 ContentResolver
.requestSync(
508 MainApp
.getAuthority(), bundle
);
510 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
511 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
512 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
513 builder
.setExpedited(true
);
514 builder
.setManual(true
);
516 SyncRequest request
= builder
.build();
517 ContentResolver
.requestSync(request
);
523 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
524 if (itemPosition
!= 0) {
525 String targetPath
= "";
526 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
527 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
529 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
530 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
531 if (targetFolder
!= null
) {
532 browseTo(targetFolder
);
535 // the next operation triggers a new call to this method, but it's necessary to
536 // ensure that the name exposed in the action bar is the current directory when the
537 // user selected it in the navigation list
538 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
539 getSupportActionBar().setSelectedNavigationItem(0);
545 * Called, when the user selected something for uploading
547 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
548 super.onActivityResult(requestCode
, resultCode
, data
);
550 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
551 requestSimpleUpload(data
, resultCode
);
553 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
554 requestMultipleUpload(data
, resultCode
);
556 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
557 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
558 requestMoveOperation(data
, resultCode
);
562 private void requestMultipleUpload(Intent data
, int resultCode
) {
563 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
564 if (filePaths
!= null
) {
565 String
[] remotePaths
= new String
[filePaths
.length
];
566 String remotePathBase
= "";
567 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
568 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
570 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
571 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
572 for (int j
= 0; j
< remotePaths
.length
; j
++) {
573 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
576 Intent i
= new Intent(this, FileUploader
.class);
577 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
578 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
579 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
580 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
581 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
582 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
586 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
587 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
594 private void requestSimpleUpload(Intent data
, int resultCode
) {
595 String filepath
= null
;
597 Uri selectedImageUri
= data
.getData();
599 String filemanagerstring
= selectedImageUri
.getPath();
600 String selectedImagePath
= getPath(selectedImageUri
);
602 if (selectedImagePath
!= null
)
603 filepath
= selectedImagePath
;
605 filepath
= filemanagerstring
;
607 } catch (Exception e
) {
608 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
612 if (filepath
== null
) {
613 Log_OC
.e(TAG
, "Couldnt resolve path to file");
614 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
620 Intent i
= new Intent(this, FileUploader
.class);
621 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
623 String remotepath
= new String();
624 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
625 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
627 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
628 remotepath
+= OCFile
.PATH_SEPARATOR
;
629 remotepath
+= new File(filepath
).getName();
631 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
632 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
633 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
634 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
635 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
640 * Request the operation for moving the file/folder from one path to another
642 * @param data Intent received
643 * @param resultCode Result code received
645 private void requestMoveOperation(Intent data
, int resultCode
) {
646 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
647 getFileOperationsHelper().moveFile(folderToMoveAt
, getCurrentDir());
651 public void onBackPressed() {
652 OCFileListFragment listOfFiles
= getListOfFilesFragment();
653 if (mDualPane
|| getSecondFragment() == null
) {
654 if (listOfFiles
!= null
) { // should never be null, indeed
655 if (mDirectories
.getCount() <= 1) {
659 int levelsUp
= listOfFiles
.onBrowseUp();
660 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
665 if (listOfFiles
!= null
) { // should never be null, indeed
666 setFile(listOfFiles
.getCurrentFile());
668 cleanSecondFragment();
673 protected void onSaveInstanceState(Bundle outState
) {
674 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
675 Log_OC
.e(TAG
, "onSaveInstanceState() start");
676 super.onSaveInstanceState(outState
);
677 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
678 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
679 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
680 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
682 Log_OC
.d(TAG
, "onSaveInstanceState() end");
688 protected void onResume() {
690 Log_OC
.e(TAG
, "onResume() start");
692 // refresh list of files
693 refreshListOfFilesFragment();
695 // Listen for sync messages
696 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
697 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
698 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
699 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
700 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
701 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
702 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
703 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
705 // Listen for upload messages
706 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
707 mUploadFinishReceiver
= new UploadFinishReceiver();
708 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
710 // Listen for download messages
711 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
712 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
713 mDownloadFinishReceiver
= new DownloadFinishReceiver();
714 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
716 Log_OC
.d(TAG
, "onResume() end");
721 protected void onPause() {
722 Log_OC
.e(TAG
, "onPause() start");
723 if (mSyncBroadcastReceiver
!= null
) {
724 unregisterReceiver(mSyncBroadcastReceiver
);
725 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
726 mSyncBroadcastReceiver
= null
;
728 if (mUploadFinishReceiver
!= null
) {
729 unregisterReceiver(mUploadFinishReceiver
);
730 mUploadFinishReceiver
= null
;
732 if (mDownloadFinishReceiver
!= null
) {
733 unregisterReceiver(mDownloadFinishReceiver
);
734 mDownloadFinishReceiver
= null
;
738 Log_OC
.d(TAG
, "onPause() end");
744 protected Dialog
onCreateDialog(int id
) {
745 Dialog dialog
= null
;
746 AlertDialog
.Builder builder
;
748 case DIALOG_SHORT_WAIT
: {
749 ProgressDialog working_dialog
= new ProgressDialog(this);
750 working_dialog
.setMessage(getResources().getString(
751 R
.string
.wait_a_moment
));
752 working_dialog
.setIndeterminate(true
);
753 working_dialog
.setCancelable(false
);
754 dialog
= working_dialog
;
757 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
760 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
761 getString(R
.string
.actionbar_upload_from_apps
) };
763 builder
= new AlertDialog
.Builder(this);
764 builder
.setTitle(R
.string
.actionbar_upload
);
765 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
766 public void onClick(DialogInterface dialog
, int item
) {
769 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
770 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
771 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
773 // TODO create and handle new fragment
774 // LocalFileListFragment
776 } else if (item
== 1) {
777 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
778 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
779 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
780 ACTION_SELECT_CONTENT_FROM_APPS
);
784 dialog
= builder
.create();
787 case DIALOG_CERT_NOT_SAVED
: {
788 builder
= new AlertDialog
.Builder(this);
789 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
790 builder
.setCancelable(false
);
791 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
793 public void onClick(DialogInterface dialog
, int which
) {
797 dialog
= builder
.create();
809 * Translates a content URI of an image to a physical path
811 * @param uri The URI to resolve
812 * @return The path to the image or null if it could not be found
814 public String
getPath(Uri uri
) {
815 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
816 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
817 if (cursor
!= null
) {
818 int column_index
= cursor
819 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
820 cursor
.moveToFirst();
821 return cursor
.getString(column_index
);
827 * Pushes a directory to the drop down list
828 * @param directory to push
829 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
831 public void pushDirname(OCFile directory
) {
832 if(!directory
.isFolder()){
833 throw new IllegalArgumentException("Only directories may be pushed!");
835 mDirectories
.insert(directory
.getFileName(), 0);
840 * Pops a directory name from the drop down list
841 * @return True, unless the stack is empty
843 public boolean popDirname() {
844 mDirectories
.remove(mDirectories
.getItem(0));
845 return !mDirectories
.isEmpty();
848 // Custom array adapter to override text colors
849 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
851 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
855 public View
getView(int position
, View convertView
, ViewGroup parent
) {
856 View v
= super.getView(position
, convertView
, parent
);
858 ((TextView
) v
).setTextColor(getResources().getColorStateList(
859 android
.R
.color
.white
));
861 fixRoot((TextView
) v
);
865 public View
getDropDownView(int position
, View convertView
,
867 View v
= super.getDropDownView(position
, convertView
, parent
);
869 ((TextView
) v
).setTextColor(getResources().getColorStateList(
870 android
.R
.color
.white
));
872 fixRoot((TextView
) v
);
876 private void fixRoot(TextView v
) {
877 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
878 v
.setText(R
.string
.default_display_name_for_root_folder
);
884 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
887 * {@link BroadcastReceiver} to enable syncing feedback in UI
890 public void onReceive(Context context
, Intent intent
) {
892 String event
= intent
.getAction();
893 Log_OC
.d(TAG
, "Received broadcast " + event
);
894 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
895 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
896 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
897 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
901 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
902 mSyncInProgress
= true
;
905 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
906 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
908 if (currentDir
== null
) {
909 // current folder was removed from the server
910 Toast
.makeText( FileDisplayActivity
.this,
911 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
917 if (currentFile
== null
&& !getFile().isFolder()) {
918 // currently selected file was removed in the server, and now we know it
919 cleanSecondFragment();
920 currentFile
= currentDir
;
923 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
924 OCFileListFragment fileListFragment
= getListOfFilesFragment();
925 if (fileListFragment
!= null
) {
926 fileListFragment
.listDirectory(currentDir
);
929 setFile(currentFile
);
932 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
934 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
936 /// TODO refactor and make common
937 synchResult
!= null
&& !synchResult
.isSuccess() &&
938 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
939 synchResult
.isIdPRedirection() ||
940 (synchResult
.isException() && synchResult
.getException()
941 instanceof AuthenticatorException
))) {
943 OwnCloudClient client
= null
;
945 OwnCloudAccount ocAccount
=
946 new OwnCloudAccount(getAccount(), context
);
947 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
948 removeClientFor(ocAccount
));
949 // TODO get rid of these exceptions
950 } catch (AccountNotFoundException e
) {
952 } catch (AuthenticatorException e
) {
954 } catch (OperationCanceledException e
) {
956 } catch (IOException e
) {
960 if (client
!= null
) {
961 OwnCloudCredentials cred
= client
.getCredentials();
963 AccountManager am
= AccountManager
.get(context
);
964 if (cred
.authTokenExpires()) {
965 am
.invalidateAuthToken(
970 am
.clearPassword(getAccount());
975 requestCredentialsUpdate();
979 removeStickyBroadcast(intent
);
980 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
981 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
987 if (synchResult
!= null
) {
988 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
989 mLastSslUntrustedServerResult
= synchResult
;
992 } catch (RuntimeException e
) {
993 // avoid app crashes after changing the serial id of RemoteOperationResult
994 // in owncloud library with broadcast notifications pending to process
995 removeStickyBroadcast(intent
);
1001 * Show a text message on screen view for notifying user if content is
1002 * loading or folder is empty
1004 private void setBackgroundText() {
1005 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1006 if (ocFileListFragment
!= null
) {
1007 int message
= R
.string
.file_list_loading
;
1008 if (!mSyncInProgress
) {
1009 // In case file list is empty
1010 message
= R
.string
.file_list_empty
;
1012 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1014 Log
.e(TAG
, "OCFileListFragment is null");
1019 * Once the file upload has finished -> update view
1021 private class UploadFinishReceiver
extends BroadcastReceiver
{
1023 * Once the file upload has finished -> update view
1024 * @author David A. Velasco
1025 * {@link BroadcastReceiver} to enable upload feedback in UI
1028 public void onReceive(Context context
, Intent intent
) {
1030 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1031 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1032 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1033 OCFile currentDir
= getCurrentDir();
1034 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1035 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1037 if (sameAccount
&& isDescendant
) {
1038 refreshListOfFilesFragment();
1041 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1042 boolean renamedInUpload
= getFile().getRemotePath().
1043 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1044 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1046 FileFragment details
= getSecondFragment();
1047 boolean detailFragmentIsShown
= (details
!= null
&&
1048 details
instanceof FileDetailFragment
);
1050 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1051 if (uploadWasFine
) {
1052 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1054 if (renamedInUpload
) {
1055 String newName
= (new File(uploadedRemotePath
)).getName();
1056 Toast msg
= Toast
.makeText(
1059 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1064 if (uploadWasFine
|| getFile().fileExists()) {
1065 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1067 cleanSecondFragment();
1070 // Force the preview if the file is an image
1071 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1072 startImagePreview(getFile());
1073 } // TODO what about other kind of previews?
1077 if (intent
!= null
) {
1078 removeStickyBroadcast(intent
);
1088 * Class waiting for broadcast events from the {@link FielDownloader} service.
1090 * Updates the UI when a download is started or finished, provided that it is relevant for the
1093 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1095 public void onReceive(Context context
, Intent intent
) {
1097 boolean sameAccount
= isSameAccount(context
, intent
);
1098 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1099 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1101 if (sameAccount
&& isDescendant
) {
1102 refreshListOfFilesFragment();
1103 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1106 if (mWaitingToSend
!= null
) {
1107 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1108 if (mWaitingToSend
.isDown()) {
1109 sendDownloadedFile();
1114 if (intent
!= null
) {
1115 removeStickyBroadcast(intent
);
1120 private boolean isDescendant(String downloadedRemotePath
) {
1121 OCFile currentDir
= getCurrentDir();
1122 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1125 private boolean isSameAccount(Context context
, Intent intent
) {
1126 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1127 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1132 public void browseToRoot() {
1133 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1134 if (listOfFiles
!= null
) { // should never be null, indeed
1135 while (mDirectories
.getCount() > 1) {
1138 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1139 listOfFiles
.listDirectory(root
);
1140 setFile(listOfFiles
.getCurrentFile());
1141 startSyncFolderOperation(root
);
1143 cleanSecondFragment();
1147 public void browseTo(OCFile folder
) {
1148 if (folder
== null
|| !folder
.isFolder()) {
1149 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1151 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1152 if (listOfFiles
!= null
) {
1153 setNavigationListWithFolder(folder
);
1154 listOfFiles
.listDirectory(folder
);
1155 setFile(listOfFiles
.getCurrentFile());
1156 startSyncFolderOperation(folder
);
1158 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1160 cleanSecondFragment();
1167 * Updates action bar and second fragment, if in dual pane mode.
1170 public void onBrowsedDownTo(OCFile directory
) {
1171 pushDirname(directory
);
1172 cleanSecondFragment();
1175 startSyncFolderOperation(directory
);
1180 * Shows the information of the {@link OCFile} received as a
1181 * parameter in the second fragment.
1183 * @param file {@link OCFile} whose details will be shown
1186 public void showDetails(OCFile file
) {
1187 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1188 setSecondFragment(detailFragment
);
1189 updateFragmentsVisibility(true
);
1190 updateNavigationElementsInActionBar(file
);
1198 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1199 ActionBar actionBar
= getSupportActionBar();
1200 if (chosenFile
== null
|| mDualPane
) {
1201 // only list of files - set for browsing through folders
1202 OCFile currentDir
= getCurrentDir();
1203 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1204 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1205 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1207 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1209 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1210 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1213 actionBar
.setDisplayHomeAsUpEnabled(true
);
1214 actionBar
.setDisplayShowTitleEnabled(true
);
1215 actionBar
.setTitle(chosenFile
.getFileName());
1216 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1222 protected ServiceConnection
newTransferenceServiceConnection() {
1223 return new ListServiceConnection();
1226 /** Defines callbacks for service binding, passed to bindService() */
1227 private class ListServiceConnection
implements ServiceConnection
{
1230 public void onServiceConnected(ComponentName component
, IBinder service
) {
1231 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1232 Log_OC
.d(TAG
, "Download service connected");
1233 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1234 if (mWaitingToPreview
!= null
)
1235 if (getStorageManager() != null
) {
1236 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1237 if (!mWaitingToPreview
.isDown()) {
1238 requestForDownload();
1242 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1243 Log_OC
.d(TAG
, "Upload service connected");
1244 mUploaderBinder
= (FileUploaderBinder
) service
;
1248 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1249 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1250 if (listOfFiles
!= null
) {
1251 listOfFiles
.listDirectory();
1253 FileFragment secondFragment
= getSecondFragment();
1254 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1255 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1256 detailFragment
.listenForTransferProgress();
1257 detailFragment
.updateFileDetails(false
, false
);
1262 public void onServiceDisconnected(ComponentName component
) {
1263 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1264 Log_OC
.d(TAG
, "Download service disconnected");
1265 mDownloaderBinder
= null
;
1266 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1267 Log_OC
.d(TAG
, "Upload service disconnected");
1268 mUploaderBinder
= null
;
1276 * Launch an intent to request the PIN code to the user before letting him use the app
1278 private void requestPinCode() {
1279 boolean pinStart
= false
;
1280 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1281 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1283 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1284 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1291 public void onSavedCertificate() {
1292 startSyncFolderOperation(getCurrentDir());
1297 public void onFailedSavingCertificate() {
1298 showDialog(DIALOG_CERT_NOT_SAVED
);
1302 public void onCancelCertificate() {
1307 * Updates the view associated to the activity after the finish of some operation over files
1308 * in the current account.
1310 * @param operation Removal operation performed.
1311 * @param result Result of the removal.
1314 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1315 super.onRemoteOperationFinish(operation
, result
);
1317 if (operation
instanceof RemoveFileOperation
) {
1318 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1320 } else if (operation
instanceof RenameFileOperation
) {
1321 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1323 } else if (operation
instanceof SynchronizeFileOperation
) {
1324 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1326 } else if (operation
instanceof CreateFolderOperation
) {
1327 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1329 } else if (operation
instanceof CreateShareOperation
) {
1330 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1332 } else if (operation
instanceof UnshareLinkOperation
) {
1333 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1340 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1341 if (result
.isSuccess()) {
1342 refreshShowDetails();
1343 refreshListOfFilesFragment();
1348 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1349 if (result
.isSuccess()) {
1350 refreshShowDetails();
1351 refreshListOfFilesFragment();
1353 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1354 cleanSecondFragment();
1355 refreshListOfFilesFragment();
1359 private void refreshShowDetails() {
1360 FileFragment details
= getSecondFragment();
1361 if (details
!= null
) {
1362 OCFile file
= details
.getFile();
1364 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1365 if (details
instanceof PreviewMediaFragment
) {
1366 // Refresh OCFile of the fragment
1367 ((PreviewMediaFragment
) details
).updateFile(file
);
1372 invalidateOptionsMenu();
1377 * Updates the view associated to the activity after the finish of an operation trying to remove a
1380 * @param operation Removal operation performed.
1381 * @param result Result of the removal.
1383 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1384 dismissLoadingDialog();
1386 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1390 if (result
.isSuccess()) {
1391 OCFile removedFile
= operation
.getFile();
1392 FileFragment second
= getSecondFragment();
1393 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1394 if (second
instanceof PreviewMediaFragment
) {
1395 ((PreviewMediaFragment
)second
).stopPreview(true
);
1397 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1398 cleanSecondFragment();
1400 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1401 refreshListOfFilesFragment();
1403 invalidateOptionsMenu();
1405 if (result
.isSslRecoverableException()) {
1406 mLastSslUntrustedServerResult
= result
;
1407 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1414 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1416 * @param operation Creation operation performed.
1417 * @param result Result of the creation.
1419 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1420 if (result
.isSuccess()) {
1421 dismissLoadingDialog();
1422 refreshListOfFilesFragment();
1424 dismissLoadingDialog();
1426 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1427 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1431 } catch (NotFoundException e
) {
1432 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1439 * Updates the view associated to the activity after the finish of an operation trying to rename a
1442 * @param operation Renaming operation performed.
1443 * @param result Result of the renaming.
1445 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1446 dismissLoadingDialog();
1447 OCFile renamedFile
= operation
.getFile();
1448 if (result
.isSuccess()) {
1449 FileFragment details
= getSecondFragment();
1450 if (details
!= null
) {
1451 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1452 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1453 showDetails(renamedFile
);
1455 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1456 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1457 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1458 int position
= ((PreviewMediaFragment
)details
).getPosition();
1459 startMediaPreview(renamedFile
, position
, true
);
1461 getFileOperationsHelper().openFile(renamedFile
);
1466 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1467 refreshListOfFilesFragment();
1471 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1475 if (result
.isSslRecoverableException()) {
1476 mLastSslUntrustedServerResult
= result
;
1477 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1482 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1483 dismissLoadingDialog();
1484 OCFile syncedFile
= operation
.getLocalFile();
1485 if (!result
.isSuccess()) {
1486 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1487 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1488 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1489 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1495 if (operation
.transferWasRequested()) {
1496 onTransferStateChanged(syncedFile
, true
, true
);
1499 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1511 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1512 refreshListOfFilesFragment();
1513 FileFragment details
= getSecondFragment();
1514 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1515 if (downloading
|| uploading
) {
1516 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1518 if (!file
.fileExists()) {
1519 cleanSecondFragment();
1521 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1529 private void requestForDownload() {
1530 Account account
= getAccount();
1531 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1532 Intent i
= new Intent(this, FileDownloader
.class);
1533 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1534 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1540 private OCFile
getCurrentDir() {
1541 OCFile file
= getFile();
1543 if (file
.isFolder()) {
1545 } else if (getStorageManager() != null
) {
1546 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1547 return getStorageManager().getFileByPath(parentPath
);
1553 public void startSyncFolderOperation(OCFile folder
) {
1554 long currentSyncTime
= System
.currentTimeMillis();
1556 mSyncInProgress
= true
;
1558 // perform folder synchronization
1559 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1562 getFileOperationsHelper().isSharedSupported(),
1563 getStorageManager(),
1565 getApplicationContext()
1567 synchFolderOp
.execute(getAccount(), this, null
, null
);
1569 setSupportProgressBarIndeterminateVisibility(true
);
1571 setBackgroundText();
1575 * Show untrusted cert dialog
1577 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1578 // Show a dialog with the certificate info
1579 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1580 FragmentManager fm
= getSupportFragmentManager();
1581 FragmentTransaction ft
= fm
.beginTransaction();
1582 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1585 private void requestForDownload(OCFile file
) {
1586 Account account
= getAccount();
1587 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1588 Intent i
= new Intent(this, FileDownloader
.class);
1589 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1590 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1595 private void sendDownloadedFile(){
1596 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1597 mWaitingToSend
= null
;
1602 * Requests the download of the received {@link OCFile} , updates the UI
1603 * to monitor the download progress and prepares the activity to send the file
1604 * when the download finishes.
1606 * @param file {@link OCFile} to download and preview.
1608 public void startDownloadForSending(OCFile file
) {
1609 mWaitingToSend
= file
;
1610 requestForDownload(mWaitingToSend
);
1611 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1612 updateFragmentsVisibility(hasSecondFragment
);
1616 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1618 * @param file Image {@link OCFile} to show.
1620 public void startImagePreview(OCFile file
) {
1621 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1622 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1623 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1624 startActivity(showDetailsIntent
);
1629 * Stars the preview of an already down media {@link OCFile}.
1631 * @param file Media {@link OCFile} to preview.
1632 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1633 * @param autoplay When 'true', the playback will start without user interactions.
1635 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1636 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1637 setSecondFragment(mediaFragment
);
1638 updateFragmentsVisibility(true
);
1639 updateNavigationElementsInActionBar(file
);
1644 * Requests the download of the received {@link OCFile} , updates the UI
1645 * to monitor the download progress and prepares the activity to preview
1646 * or open the file when the download finishes.
1648 * @param file {@link OCFile} to download and preview.
1650 public void startDownloadForPreview(OCFile file
) {
1651 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1652 setSecondFragment(detailFragment
);
1653 mWaitingToPreview
= file
;
1654 requestForDownload();
1655 updateFragmentsVisibility(true
);
1656 updateNavigationElementsInActionBar(file
);
1661 public void cancelTransference(OCFile file
) {
1662 getFileOperationsHelper().cancelTransference(file
);
1663 if (mWaitingToPreview
!= null
&&
1664 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1665 mWaitingToPreview
= null
;
1667 if (mWaitingToSend
!= null
&&
1668 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1669 mWaitingToSend
= null
;
1671 onTransferStateChanged(file
, false
, false
);
1675 public void onRefresh() {
1676 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1677 if (listOfFiles
!= null
) {
1678 OCFile folder
= listOfFiles
.getCurrentFile();
1679 if (folder
!= null
) {
1680 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1681 listDirectory(mFile);*/
1682 startSyncFolderOperation(folder
);