1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.util
.Log
;
52 import android
.view
.View
;
53 import android
.view
.ViewGroup
;
54 import android
.widget
.ArrayAdapter
;
55 import android
.widget
.TextView
;
56 import android
.widget
.Toast
;
58 import com
.actionbarsherlock
.app
.ActionBar
;
59 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
60 import com
.actionbarsherlock
.view
.Menu
;
61 import com
.actionbarsherlock
.view
.MenuInflater
;
62 import com
.actionbarsherlock
.view
.MenuItem
;
63 import com
.actionbarsherlock
.view
.Window
;
64 import com
.owncloud
.android
.MainApp
;
65 import com
.owncloud
.android
.R
;
66 import com
.owncloud
.android
.datamodel
.OCFile
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
81 import com
.owncloud
.android
.operations
.CreateShareOperation
;
82 import com
.owncloud
.android
.operations
.MoveFileOperation
;
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
, OnEnforceableRefreshListener
{
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
, false
);
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
)){
559 final Intent fData
= data
;
560 final int fResultCode
= resultCode
;
561 getHandler().postDelayed(
565 requestMoveOperation(fData
, fResultCode
);
568 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
573 private void requestMultipleUpload(Intent data
, int resultCode
) {
574 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
575 if (filePaths
!= null
) {
576 String
[] remotePaths
= new String
[filePaths
.length
];
577 String remotePathBase
= "";
578 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
579 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
581 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
582 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
583 for (int j
= 0; j
< remotePaths
.length
; j
++) {
584 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
587 Intent i
= new Intent(this, FileUploader
.class);
588 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
589 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
590 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
591 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
592 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
593 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
597 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
598 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
605 private void requestSimpleUpload(Intent data
, int resultCode
) {
606 String filepath
= null
;
608 Uri selectedImageUri
= data
.getData();
610 String filemanagerstring
= selectedImageUri
.getPath();
611 String selectedImagePath
= getPath(selectedImageUri
);
613 if (selectedImagePath
!= null
)
614 filepath
= selectedImagePath
;
616 filepath
= filemanagerstring
;
618 } catch (Exception e
) {
619 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
623 if (filepath
== null
) {
624 Log_OC
.e(TAG
, "Couldnt resolve path to file");
625 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
631 Intent i
= new Intent(this, FileUploader
.class);
632 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
634 String remotepath
= new String();
635 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
636 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
638 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
639 remotepath
+= OCFile
.PATH_SEPARATOR
;
640 remotepath
+= new File(filepath
).getName();
642 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
643 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
644 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
645 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
646 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
651 * Request the operation for moving the file/folder from one path to another
653 * @param data Intent received
654 * @param resultCode Result code received
656 private void requestMoveOperation(Intent data
, int resultCode
) {
657 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
658 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
659 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
663 public void onBackPressed() {
664 OCFileListFragment listOfFiles
= getListOfFilesFragment();
665 if (mDualPane
|| getSecondFragment() == null
) {
666 if (listOfFiles
!= null
) { // should never be null, indeed
667 if (mDirectories
.getCount() <= 1) {
671 int levelsUp
= listOfFiles
.onBrowseUp();
672 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
677 if (listOfFiles
!= null
) { // should never be null, indeed
678 setFile(listOfFiles
.getCurrentFile());
680 cleanSecondFragment();
685 protected void onSaveInstanceState(Bundle outState
) {
686 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
687 Log_OC
.e(TAG
, "onSaveInstanceState() start");
688 super.onSaveInstanceState(outState
);
689 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
690 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
691 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
692 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
694 Log_OC
.d(TAG
, "onSaveInstanceState() end");
700 protected void onResume() {
702 Log_OC
.e(TAG
, "onResume() start");
704 // refresh list of files
705 refreshListOfFilesFragment();
707 // Listen for sync messages
708 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
709 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
710 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
711 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
712 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
713 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
714 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
715 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
717 // Listen for upload messages
718 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
719 mUploadFinishReceiver
= new UploadFinishReceiver();
720 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
722 // Listen for download messages
723 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
724 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
725 mDownloadFinishReceiver
= new DownloadFinishReceiver();
726 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
728 Log_OC
.d(TAG
, "onResume() end");
733 protected void onPause() {
734 Log_OC
.e(TAG
, "onPause() start");
735 if (mSyncBroadcastReceiver
!= null
) {
736 unregisterReceiver(mSyncBroadcastReceiver
);
737 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
738 mSyncBroadcastReceiver
= null
;
740 if (mUploadFinishReceiver
!= null
) {
741 unregisterReceiver(mUploadFinishReceiver
);
742 mUploadFinishReceiver
= null
;
744 if (mDownloadFinishReceiver
!= null
) {
745 unregisterReceiver(mDownloadFinishReceiver
);
746 mDownloadFinishReceiver
= null
;
750 Log_OC
.d(TAG
, "onPause() end");
756 protected Dialog
onCreateDialog(int id
) {
757 Dialog dialog
= null
;
758 AlertDialog
.Builder builder
;
760 case DIALOG_SHORT_WAIT
: {
761 ProgressDialog working_dialog
= new ProgressDialog(this);
762 working_dialog
.setMessage(getResources().getString(
763 R
.string
.wait_a_moment
));
764 working_dialog
.setIndeterminate(true
);
765 working_dialog
.setCancelable(false
);
766 dialog
= working_dialog
;
769 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
772 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
773 getString(R
.string
.actionbar_upload_from_apps
) };
775 builder
= new AlertDialog
.Builder(this);
776 builder
.setTitle(R
.string
.actionbar_upload
);
777 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
778 public void onClick(DialogInterface dialog
, int item
) {
781 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
782 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
783 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
785 // TODO create and handle new fragment
786 // LocalFileListFragment
788 } else if (item
== 1) {
789 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
790 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
791 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
792 ACTION_SELECT_CONTENT_FROM_APPS
);
796 dialog
= builder
.create();
799 case DIALOG_CERT_NOT_SAVED
: {
800 builder
= new AlertDialog
.Builder(this);
801 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
802 builder
.setCancelable(false
);
803 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
805 public void onClick(DialogInterface dialog
, int which
) {
809 dialog
= builder
.create();
821 * Translates a content URI of an image to a physical path
823 * @param uri The URI to resolve
824 * @return The path to the image or null if it could not be found
826 public String
getPath(Uri uri
) {
827 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
828 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
829 if (cursor
!= null
) {
830 int column_index
= cursor
831 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
832 cursor
.moveToFirst();
833 return cursor
.getString(column_index
);
839 * Pushes a directory to the drop down list
840 * @param directory to push
841 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
843 public void pushDirname(OCFile directory
) {
844 if(!directory
.isFolder()){
845 throw new IllegalArgumentException("Only directories may be pushed!");
847 mDirectories
.insert(directory
.getFileName(), 0);
852 * Pops a directory name from the drop down list
853 * @return True, unless the stack is empty
855 public boolean popDirname() {
856 mDirectories
.remove(mDirectories
.getItem(0));
857 return !mDirectories
.isEmpty();
860 // Custom array adapter to override text colors
861 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
863 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
867 public View
getView(int position
, View convertView
, ViewGroup parent
) {
868 View v
= super.getView(position
, convertView
, parent
);
870 ((TextView
) v
).setTextColor(getResources().getColorStateList(
871 android
.R
.color
.white
));
873 fixRoot((TextView
) v
);
877 public View
getDropDownView(int position
, View convertView
,
879 View v
= super.getDropDownView(position
, convertView
, parent
);
881 ((TextView
) v
).setTextColor(getResources().getColorStateList(
882 android
.R
.color
.white
));
884 fixRoot((TextView
) v
);
888 private void fixRoot(TextView v
) {
889 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
890 v
.setText(R
.string
.default_display_name_for_root_folder
);
896 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
899 * {@link BroadcastReceiver} to enable syncing feedback in UI
902 public void onReceive(Context context
, Intent intent
) {
904 String event
= intent
.getAction();
905 Log_OC
.d(TAG
, "Received broadcast " + event
);
906 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
907 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
908 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
909 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
913 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
914 mSyncInProgress
= true
;
917 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
918 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
920 if (currentDir
== null
) {
921 // current folder was removed from the server
922 Toast
.makeText( FileDisplayActivity
.this,
923 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
929 if (currentFile
== null
&& !getFile().isFolder()) {
930 // currently selected file was removed in the server, and now we know it
931 cleanSecondFragment();
932 currentFile
= currentDir
;
935 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
936 OCFileListFragment fileListFragment
= getListOfFilesFragment();
937 if (fileListFragment
!= null
) {
938 fileListFragment
.listDirectory(currentDir
);
941 setFile(currentFile
);
944 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
946 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
948 /// TODO refactor and make common
949 synchResult
!= null
&& !synchResult
.isSuccess() &&
950 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
951 synchResult
.isIdPRedirection() ||
952 (synchResult
.isException() && synchResult
.getException()
953 instanceof AuthenticatorException
))) {
955 OwnCloudClient client
= null
;
957 OwnCloudAccount ocAccount
=
958 new OwnCloudAccount(getAccount(), context
);
959 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
960 removeClientFor(ocAccount
));
961 // TODO get rid of these exceptions
962 } catch (AccountNotFoundException e
) {
964 } catch (AuthenticatorException e
) {
966 } catch (OperationCanceledException e
) {
968 } catch (IOException e
) {
972 if (client
!= null
) {
973 OwnCloudCredentials cred
= client
.getCredentials();
975 AccountManager am
= AccountManager
.get(context
);
976 if (cred
.authTokenExpires()) {
977 am
.invalidateAuthToken(
982 am
.clearPassword(getAccount());
987 requestCredentialsUpdate();
991 removeStickyBroadcast(intent
);
992 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
993 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
999 if (synchResult
!= null
) {
1000 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1001 mLastSslUntrustedServerResult
= synchResult
;
1004 } catch (RuntimeException e
) {
1005 // avoid app crashes after changing the serial id of RemoteOperationResult
1006 // in owncloud library with broadcast notifications pending to process
1007 removeStickyBroadcast(intent
);
1013 * Show a text message on screen view for notifying user if content is
1014 * loading or folder is empty
1016 private void setBackgroundText() {
1017 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1018 if (ocFileListFragment
!= null
) {
1019 int message
= R
.string
.file_list_loading
;
1020 if (!mSyncInProgress
) {
1021 // In case file list is empty
1022 message
= R
.string
.file_list_empty
;
1024 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1026 Log
.e(TAG
, "OCFileListFragment is null");
1031 * Once the file upload has finished -> update view
1033 private class UploadFinishReceiver
extends BroadcastReceiver
{
1035 * Once the file upload has finished -> update view
1036 * @author David A. Velasco
1037 * {@link BroadcastReceiver} to enable upload feedback in UI
1040 public void onReceive(Context context
, Intent intent
) {
1042 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1043 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1044 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1045 OCFile currentDir
= getCurrentDir();
1046 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1047 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1049 if (sameAccount
&& isDescendant
) {
1050 refreshListOfFilesFragment();
1053 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1054 boolean renamedInUpload
= getFile().getRemotePath().
1055 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1056 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1058 FileFragment details
= getSecondFragment();
1059 boolean detailFragmentIsShown
= (details
!= null
&&
1060 details
instanceof FileDetailFragment
);
1062 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1063 if (uploadWasFine
) {
1064 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1066 if (renamedInUpload
) {
1067 String newName
= (new File(uploadedRemotePath
)).getName();
1068 Toast msg
= Toast
.makeText(
1071 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1076 if (uploadWasFine
|| getFile().fileExists()) {
1077 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1079 cleanSecondFragment();
1082 // Force the preview if the file is an image
1083 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1084 startImagePreview(getFile());
1085 } // TODO what about other kind of previews?
1089 if (intent
!= null
) {
1090 removeStickyBroadcast(intent
);
1100 * Class waiting for broadcast events from the {@link FielDownloader} service.
1102 * Updates the UI when a download is started or finished, provided that it is relevant for the
1105 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1107 public void onReceive(Context context
, Intent intent
) {
1109 boolean sameAccount
= isSameAccount(context
, intent
);
1110 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1111 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1113 if (sameAccount
&& isDescendant
) {
1114 refreshListOfFilesFragment();
1115 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1118 if (mWaitingToSend
!= null
) {
1119 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1120 if (mWaitingToSend
.isDown()) {
1121 sendDownloadedFile();
1126 if (intent
!= null
) {
1127 removeStickyBroadcast(intent
);
1132 private boolean isDescendant(String downloadedRemotePath
) {
1133 OCFile currentDir
= getCurrentDir();
1134 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1137 private boolean isSameAccount(Context context
, Intent intent
) {
1138 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1139 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1144 public void browseToRoot() {
1145 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1146 if (listOfFiles
!= null
) { // should never be null, indeed
1147 while (mDirectories
.getCount() > 1) {
1150 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1151 listOfFiles
.listDirectory(root
);
1152 setFile(listOfFiles
.getCurrentFile());
1153 startSyncFolderOperation(root
, false
);
1155 cleanSecondFragment();
1159 public void browseTo(OCFile folder
) {
1160 if (folder
== null
|| !folder
.isFolder()) {
1161 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1163 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1164 if (listOfFiles
!= null
) {
1165 setNavigationListWithFolder(folder
);
1166 listOfFiles
.listDirectory(folder
);
1167 setFile(listOfFiles
.getCurrentFile());
1168 startSyncFolderOperation(folder
, false
);
1170 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1172 cleanSecondFragment();
1179 * Updates action bar and second fragment, if in dual pane mode.
1182 public void onBrowsedDownTo(OCFile directory
) {
1183 pushDirname(directory
);
1184 cleanSecondFragment();
1187 startSyncFolderOperation(directory
, false
);
1192 * Shows the information of the {@link OCFile} received as a
1193 * parameter in the second fragment.
1195 * @param file {@link OCFile} whose details will be shown
1198 public void showDetails(OCFile file
) {
1199 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1200 setSecondFragment(detailFragment
);
1201 updateFragmentsVisibility(true
);
1202 updateNavigationElementsInActionBar(file
);
1210 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1211 ActionBar actionBar
= getSupportActionBar();
1212 if (chosenFile
== null
|| mDualPane
) {
1213 // only list of files - set for browsing through folders
1214 OCFile currentDir
= getCurrentDir();
1215 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1216 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1217 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1219 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1221 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1222 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1225 actionBar
.setDisplayHomeAsUpEnabled(true
);
1226 actionBar
.setDisplayShowTitleEnabled(true
);
1227 actionBar
.setTitle(chosenFile
.getFileName());
1228 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1234 protected ServiceConnection
newTransferenceServiceConnection() {
1235 return new ListServiceConnection();
1238 /** Defines callbacks for service binding, passed to bindService() */
1239 private class ListServiceConnection
implements ServiceConnection
{
1242 public void onServiceConnected(ComponentName component
, IBinder service
) {
1243 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1244 Log_OC
.d(TAG
, "Download service connected");
1245 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1246 if (mWaitingToPreview
!= null
)
1247 if (getStorageManager() != null
) {
1248 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1249 if (!mWaitingToPreview
.isDown()) {
1250 requestForDownload();
1254 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1255 Log_OC
.d(TAG
, "Upload service connected");
1256 mUploaderBinder
= (FileUploaderBinder
) service
;
1260 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1261 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1262 if (listOfFiles
!= null
) {
1263 listOfFiles
.listDirectory();
1265 FileFragment secondFragment
= getSecondFragment();
1266 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1267 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1268 detailFragment
.listenForTransferProgress();
1269 detailFragment
.updateFileDetails(false
, false
);
1274 public void onServiceDisconnected(ComponentName component
) {
1275 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1276 Log_OC
.d(TAG
, "Download service disconnected");
1277 mDownloaderBinder
= null
;
1278 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1279 Log_OC
.d(TAG
, "Upload service disconnected");
1280 mUploaderBinder
= null
;
1288 * Launch an intent to request the PIN code to the user before letting him use the app
1290 private void requestPinCode() {
1291 boolean pinStart
= false
;
1292 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1293 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1295 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1296 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1303 public void onSavedCertificate() {
1304 startSyncFolderOperation(getCurrentDir(), false
);
1309 public void onFailedSavingCertificate() {
1310 showDialog(DIALOG_CERT_NOT_SAVED
);
1314 public void onCancelCertificate() {
1319 * Updates the view associated to the activity after the finish of some operation over files
1320 * in the current account.
1322 * @param operation Removal operation performed.
1323 * @param result Result of the removal.
1326 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1327 super.onRemoteOperationFinish(operation
, result
);
1329 if (operation
instanceof RemoveFileOperation
) {
1330 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1332 } else if (operation
instanceof RenameFileOperation
) {
1333 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1335 } else if (operation
instanceof SynchronizeFileOperation
) {
1336 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1338 } else if (operation
instanceof CreateFolderOperation
) {
1339 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1341 } else if (operation
instanceof CreateShareOperation
) {
1342 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1344 } else if (operation
instanceof UnshareLinkOperation
) {
1345 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1347 } else if (operation
instanceof MoveFileOperation
) {
1348 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1354 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1355 if (result
.isSuccess()) {
1356 refreshShowDetails();
1357 refreshListOfFilesFragment();
1362 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1363 if (result
.isSuccess()) {
1364 refreshShowDetails();
1365 refreshListOfFilesFragment();
1367 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1368 cleanSecondFragment();
1369 refreshListOfFilesFragment();
1373 private void refreshShowDetails() {
1374 FileFragment details
= getSecondFragment();
1375 if (details
!= null
) {
1376 OCFile file
= details
.getFile();
1378 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1379 if (details
instanceof PreviewMediaFragment
) {
1380 // Refresh OCFile of the fragment
1381 ((PreviewMediaFragment
) details
).updateFile(file
);
1386 invalidateOptionsMenu();
1391 * Updates the view associated to the activity after the finish of an operation trying to remove a
1394 * @param operation Removal operation performed.
1395 * @param result Result of the removal.
1397 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1398 dismissLoadingDialog();
1400 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1404 if (result
.isSuccess()) {
1405 OCFile removedFile
= operation
.getFile();
1406 FileFragment second
= getSecondFragment();
1407 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1408 if (second
instanceof PreviewMediaFragment
) {
1409 ((PreviewMediaFragment
)second
).stopPreview(true
);
1411 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1412 cleanSecondFragment();
1414 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1415 refreshListOfFilesFragment();
1417 invalidateOptionsMenu();
1419 if (result
.isSslRecoverableException()) {
1420 mLastSslUntrustedServerResult
= result
;
1421 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1428 * Updates the view associated to the activity after the finish of an operation trying to move a
1431 * @param operation Move operation performed.
1432 * @param result Result of the move operation.
1434 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1435 if (result
.isSuccess()) {
1436 dismissLoadingDialog();
1437 refreshListOfFilesFragment();
1439 dismissLoadingDialog();
1441 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1442 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1446 } catch (NotFoundException e
) {
1447 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1454 * Updates the view associated to the activity after the finish of an operation trying to rename a
1457 * @param operation Renaming operation performed.
1458 * @param result Result of the renaming.
1460 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1461 dismissLoadingDialog();
1462 OCFile renamedFile
= operation
.getFile();
1463 if (result
.isSuccess()) {
1464 FileFragment details
= getSecondFragment();
1465 if (details
!= null
) {
1466 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1467 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1468 showDetails(renamedFile
);
1470 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1471 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1472 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1473 int position
= ((PreviewMediaFragment
)details
).getPosition();
1474 startMediaPreview(renamedFile
, position
, true
);
1476 getFileOperationsHelper().openFile(renamedFile
);
1481 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1482 refreshListOfFilesFragment();
1486 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1490 if (result
.isSslRecoverableException()) {
1491 mLastSslUntrustedServerResult
= result
;
1492 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1497 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1498 dismissLoadingDialog();
1499 OCFile syncedFile
= operation
.getLocalFile();
1500 if (!result
.isSuccess()) {
1501 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1502 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1503 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1504 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1510 if (operation
.transferWasRequested()) {
1511 onTransferStateChanged(syncedFile
, true
, true
);
1514 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1522 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1524 * @param operation Creation operation performed.
1525 * @param result Result of the creation.
1527 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1528 if (result
.isSuccess()) {
1529 dismissLoadingDialog();
1530 refreshListOfFilesFragment();
1532 dismissLoadingDialog();
1534 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1535 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1539 } catch (NotFoundException e
) {
1540 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1550 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1551 refreshListOfFilesFragment();
1552 FileFragment details
= getSecondFragment();
1553 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1554 if (downloading
|| uploading
) {
1555 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1557 if (!file
.fileExists()) {
1558 cleanSecondFragment();
1560 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1568 private void requestForDownload() {
1569 Account account
= getAccount();
1570 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1571 Intent i
= new Intent(this, FileDownloader
.class);
1572 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1573 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1579 private OCFile
getCurrentDir() {
1580 OCFile file
= getFile();
1582 if (file
.isFolder()) {
1584 } else if (getStorageManager() != null
) {
1585 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1586 return getStorageManager().getFileByPath(parentPath
);
1592 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1593 long currentSyncTime
= System
.currentTimeMillis();
1595 mSyncInProgress
= true
;
1597 // perform folder synchronization
1598 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1601 getFileOperationsHelper().isSharedSupported(),
1603 getStorageManager(),
1605 getApplicationContext()
1607 synchFolderOp
.execute(getAccount(), this, null
, null
);
1609 setSupportProgressBarIndeterminateVisibility(true
);
1611 setBackgroundText();
1615 * Show untrusted cert dialog
1617 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1618 // Show a dialog with the certificate info
1619 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1620 FragmentManager fm
= getSupportFragmentManager();
1621 FragmentTransaction ft
= fm
.beginTransaction();
1622 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1625 private void requestForDownload(OCFile file
) {
1626 Account account
= getAccount();
1627 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1628 Intent i
= new Intent(this, FileDownloader
.class);
1629 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1630 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1635 private void sendDownloadedFile(){
1636 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1637 mWaitingToSend
= null
;
1642 * Requests the download of the received {@link OCFile} , updates the UI
1643 * to monitor the download progress and prepares the activity to send the file
1644 * when the download finishes.
1646 * @param file {@link OCFile} to download and preview.
1648 public void startDownloadForSending(OCFile file
) {
1649 mWaitingToSend
= file
;
1650 requestForDownload(mWaitingToSend
);
1651 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1652 updateFragmentsVisibility(hasSecondFragment
);
1656 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1658 * @param file Image {@link OCFile} to show.
1660 public void startImagePreview(OCFile file
) {
1661 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1662 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1663 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1664 startActivity(showDetailsIntent
);
1669 * Stars the preview of an already down media {@link OCFile}.
1671 * @param file Media {@link OCFile} to preview.
1672 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1673 * @param autoplay When 'true', the playback will start without user interactions.
1675 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1676 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1677 setSecondFragment(mediaFragment
);
1678 updateFragmentsVisibility(true
);
1679 updateNavigationElementsInActionBar(file
);
1684 * Requests the download of the received {@link OCFile} , updates the UI
1685 * to monitor the download progress and prepares the activity to preview
1686 * or open the file when the download finishes.
1688 * @param file {@link OCFile} to download and preview.
1690 public void startDownloadForPreview(OCFile file
) {
1691 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1692 setSecondFragment(detailFragment
);
1693 mWaitingToPreview
= file
;
1694 requestForDownload();
1695 updateFragmentsVisibility(true
);
1696 updateNavigationElementsInActionBar(file
);
1701 public void cancelTransference(OCFile file
) {
1702 getFileOperationsHelper().cancelTransference(file
);
1703 if (mWaitingToPreview
!= null
&&
1704 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1705 mWaitingToPreview
= null
;
1707 if (mWaitingToSend
!= null
&&
1708 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1709 mWaitingToSend
= null
;
1711 onTransferStateChanged(file
, false
, false
);
1715 public void onRefresh(boolean ignoreETag
) {
1716 refreshList(ignoreETag
);
1720 public void onRefresh() {
1724 private void refreshList(boolean ignoreETag
) {
1725 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1726 if (listOfFiles
!= null
) {
1727 OCFile folder
= listOfFiles
.getCurrentFile();
1728 if (folder
!= null
) {
1729 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1730 listDirectory(mFile);*/
1731 startSyncFolderOperation(folder
, ignoreETag
);