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
.BuildConfig
;
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
.lib
.common
.utils
.Log_OC
;
82 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
83 import com
.owncloud
.android
.operations
.CreateShareOperation
;
84 import com
.owncloud
.android
.operations
.MoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
89 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
90 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
91 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
102 import com
.owncloud
.android
.utils
.DisplayUtils
;
103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
107 * Displays, what files the user has available in his ownCloud.
109 * @author Bartek Przybylski
110 * @author David A. Velasco
113 public class FileDisplayActivity
extends HookActivity
implements
114 FileFragment
.ContainerActivity
, OnNavigationListener
,
115 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
117 private ArrayAdapter
<String
> mDirectories
;
119 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
120 private UploadFinishReceiver mUploadFinishReceiver
;
121 private DownloadFinishReceiver mDownloadFinishReceiver
;
122 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
124 private boolean mDualPane
;
125 private View mLeftFragmentContainer
;
126 private View mRightFragmentContainer
;
128 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
129 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
130 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
132 public static final int DIALOG_SHORT_WAIT
= 0;
133 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
134 private static final int DIALOG_CERT_NOT_SAVED
= 2;
136 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
138 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
139 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
140 public static final int ACTION_MOVE_FILES
= 3;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private String DIALOG_UNTRUSTED_CERT
;
153 private OCFile mWaitingToSend
;
156 protected void onCreate(Bundle savedInstanceState
) {
157 Log_OC
.d(TAG
, "onCreate() start");
158 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
160 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
162 // PIN CODE request ; best location is to decide, let's try this first
163 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
165 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
169 /// grant that FileObserverService is watching favourite files
170 if (savedInstanceState
== null
) {
171 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
172 startService(initObserversIntent
);
175 /// Load of saved instance state
176 if(savedInstanceState
!= null
) {
177 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
178 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
179 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
182 mWaitingToPreview
= null
;
183 mSyncInProgress
= false
;
184 mWaitingToSend
= null
;
189 // Inflate and set the layout view
190 setContentView(R
.layout
.files
);
191 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
192 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
193 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
194 if (savedInstanceState
== null
) {
195 createMinFragments();
199 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
200 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
201 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
205 Log_OC
.d(TAG
, "onCreate() end");
209 protected void onStart() {
211 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 protected void onDestroy() {
220 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
223 protected void onAccountSet(boolean stateWasRecovered
) {
224 super.onAccountSet(stateWasRecovered
);
225 if (getAccount() != null
) {
226 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
227 OCFile file
= getFile();
228 // get parent from path
229 String parentPath
= "";
231 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
232 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
233 // get parent from path
234 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
235 if (getStorageManager().getFileByPath(parentPath
) == null
)
236 file
= null
; // not able to know the directory where the file is uploading
238 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
242 // fall back to root folder
243 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
246 setNavigationListWithFolder(file
);
248 if (!stateWasRecovered
) {
249 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
250 initFragmentsWithFile();
251 if (file
.isFolder()) {
252 startSyncFolderOperation(file
, false
);
256 updateFragmentsVisibility(!file
.isFolder());
257 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
263 private void setNavigationListWithFolder(OCFile file
) {
264 mDirectories
.clear();
265 OCFile fileIt
= file
;
267 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
268 if (fileIt
.isFolder()) {
269 mDirectories
.add(fileIt
.getFileName());
271 // get parent from path
272 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
273 fileIt
= getStorageManager().getFileByPath(parentPath
);
275 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
279 private void createMinFragments() {
280 OCFileListFragment listOfFiles
= new OCFileListFragment();
281 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
282 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
283 transaction
.commit();
286 private void initFragmentsWithFile() {
287 if (getAccount() != null
&& getFile() != null
) {
289 OCFileListFragment listOfFiles
= getListOfFilesFragment();
290 if (listOfFiles
!= null
) {
291 listOfFiles
.listDirectory(getCurrentDir());
293 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
297 OCFile file
= getFile();
298 Fragment secondFragment
= chooseInitialSecondFragment(file
);
299 if (secondFragment
!= null
) {
300 setSecondFragment(secondFragment
);
301 updateFragmentsVisibility(true
);
302 updateNavigationElementsInActionBar(file
);
305 cleanSecondFragment();
309 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
310 if (getAccount() == null
) {
311 Log_OC
.wtf(TAG
, "\t account is NULL");
313 if (getFile() == null
) {
314 Log_OC
.wtf(TAG
, "\t file is NULL");
319 private Fragment
chooseInitialSecondFragment(OCFile file
) {
320 Fragment secondFragment
= null
;
321 if (file
!= null
&& !file
.isFolder()) {
322 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
323 && file
.getLastSyncDateForProperties() > 0 // temporal fix
325 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
326 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
327 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
330 secondFragment
= new FileDetailFragment(file
, getAccount());
333 return secondFragment
;
338 * Replaces the second fragment managed by the activity with the received as
341 * Assumes never will be more than two fragments managed at the same time.
343 * @param fragment New second Fragment to set.
345 private void setSecondFragment(Fragment fragment
) {
346 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
347 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
348 transaction
.commit();
352 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
354 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
355 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
357 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
361 } else if (existsSecondFragment
) {
362 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
363 mLeftFragmentContainer
.setVisibility(View
.GONE
);
365 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
370 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
374 mRightFragmentContainer
.setVisibility(View
.GONE
);
380 private OCFileListFragment
getListOfFilesFragment() {
381 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
382 if (listOfFiles
!= null
) {
383 return (OCFileListFragment
)listOfFiles
;
385 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
389 public FileFragment
getSecondFragment() {
390 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
391 if (second
!= null
) {
392 return (FileFragment
)second
;
397 protected void cleanSecondFragment() {
398 Fragment second
= getSecondFragment();
399 if (second
!= null
) {
400 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
404 updateFragmentsVisibility(false
);
405 updateNavigationElementsInActionBar(null
);
408 protected void refreshListOfFilesFragment() {
409 OCFileListFragment fileListFragment
= getListOfFilesFragment();
410 if (fileListFragment
!= null
) {
411 fileListFragment
.listDirectory();
415 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
416 FileFragment secondFragment
= getSecondFragment();
417 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
418 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
419 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
420 OCFile fileInFragment
= detailsFragment
.getFile();
421 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
422 // the user browsed to other file ; forget the automatic preview
423 mWaitingToPreview
= null
;
425 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
426 // grant that the right panel updates the progress bar
427 detailsFragment
.listenForTransferProgress();
428 detailsFragment
.updateFileDetails(true
, false
);
430 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
431 // update the right panel
432 boolean detailsFragmentChanged
= false
;
435 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
436 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
437 startMediaPreview(mWaitingToPreview
, 0, true
);
438 detailsFragmentChanged
= true
;
440 getFileOperationsHelper().openFile(mWaitingToPreview
);
443 mWaitingToPreview
= null
;
445 if (!detailsFragmentChanged
) {
446 detailsFragment
.updateFileDetails(false
, (success
));
453 public boolean onPrepareOptionsMenu(Menu menu
) {
454 if (BuildConfig
.DEBUG
) {
455 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
457 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
459 return super.onPrepareOptionsMenu(menu
);
463 public boolean onCreateOptionsMenu(Menu menu
) {
464 MenuInflater inflater
= getSherlock().getMenuInflater();
465 inflater
.inflate(R
.menu
.main_menu
, menu
);
470 public boolean onOptionsItemSelected(MenuItem item
) {
471 boolean retval
= true
;
472 switch (item
.getItemId()) {
473 case R
.id
.action_create_dir
: {
474 CreateFolderDialogFragment dialog
=
475 CreateFolderDialogFragment
.newInstance(getCurrentDir());
476 dialog
.show(getSupportFragmentManager(), "createdirdialog");
479 case R
.id
.action_sync_account
: {
480 startSynchronization();
483 case R
.id
.action_upload
: {
484 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
487 case R
.id
.action_settings
: {
488 Intent settingsIntent
= new Intent(this, Preferences
.class);
489 startActivity(settingsIntent
);
492 case R
.id
.action_logger
: {
493 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
494 startActivity(loggerIntent
);
497 case android
.R
.id
.home
: {
498 FileFragment second
= getSecondFragment();
499 OCFile currentDir
= getCurrentDir();
500 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
501 (second
!= null
&& second
.getFile() != null
)) {
508 retval
= super.onOptionsItemSelected(item
);
513 private void startSynchronization() {
514 Log_OC
.e(TAG
, "Got to start sync");
515 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
516 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
517 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
518 Bundle bundle
= new Bundle();
519 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
520 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
521 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
522 ContentResolver
.requestSync(
524 MainApp
.getAuthority(), bundle
);
526 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
527 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
528 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
529 builder
.setExpedited(true
);
530 builder
.setManual(true
);
532 SyncRequest request
= builder
.build();
533 ContentResolver
.requestSync(request
);
539 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
540 if (itemPosition
!= 0) {
541 String targetPath
= "";
542 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
543 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
545 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
546 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
547 if (targetFolder
!= null
) {
548 browseTo(targetFolder
);
551 // the next operation triggers a new call to this method, but it's necessary to
552 // ensure that the name exposed in the action bar is the current directory when the
553 // user selected it in the navigation list
554 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
555 getSupportActionBar().setSelectedNavigationItem(0);
561 * Called, when the user selected something for uploading
563 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
564 super.onActivityResult(requestCode
, resultCode
, data
);
566 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
567 requestSimpleUpload(data
, resultCode
);
569 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
570 requestMultipleUpload(data
, resultCode
);
572 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
573 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
575 final Intent fData
= data
;
576 final int fResultCode
= resultCode
;
577 getHandler().postDelayed(
581 requestMoveOperation(fData
, fResultCode
);
584 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
589 private void requestMultipleUpload(Intent data
, int resultCode
) {
590 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
591 if (filePaths
!= null
) {
592 String
[] remotePaths
= new String
[filePaths
.length
];
593 String remotePathBase
= "";
594 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
595 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
597 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
598 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
599 for (int j
= 0; j
< remotePaths
.length
; j
++) {
600 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
603 Intent i
= new Intent(this, FileUploader
.class);
604 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
605 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
606 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
607 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
608 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
609 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
613 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
614 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
621 private void requestSimpleUpload(Intent data
, int resultCode
) {
622 String filepath
= null
;
624 Uri selectedImageUri
= data
.getData();
626 String filemanagerstring
= selectedImageUri
.getPath();
627 String selectedImagePath
= getPath(selectedImageUri
);
629 if (selectedImagePath
!= null
)
630 filepath
= selectedImagePath
;
632 filepath
= filemanagerstring
;
634 } catch (Exception e
) {
635 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
639 if (filepath
== null
) {
640 Log_OC
.e(TAG
, "Couldnt resolve path to file");
641 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
647 Intent i
= new Intent(this, FileUploader
.class);
648 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
650 String remotepath
= new String();
651 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
652 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
654 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
655 remotepath
+= OCFile
.PATH_SEPARATOR
;
656 remotepath
+= new File(filepath
).getName();
658 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
659 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
660 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
661 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
662 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
667 * Request the operation for moving the file/folder from one path to another
669 * @param data Intent received
670 * @param resultCode Result code received
672 private void requestMoveOperation(Intent data
, int resultCode
) {
673 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
674 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
675 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
679 public void onBackPressed() {
680 OCFileListFragment listOfFiles
= getListOfFilesFragment();
681 if (mDualPane
|| getSecondFragment() == null
) {
682 if (listOfFiles
!= null
) { // should never be null, indeed
683 if (mDirectories
.getCount() <= 1) {
687 int levelsUp
= listOfFiles
.onBrowseUp();
688 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
693 if (listOfFiles
!= null
) { // should never be null, indeed
694 setFile(listOfFiles
.getCurrentFile());
696 cleanSecondFragment();
701 protected void onSaveInstanceState(Bundle outState
) {
702 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
703 Log_OC
.e(TAG
, "onSaveInstanceState() start");
704 super.onSaveInstanceState(outState
);
705 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
706 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
707 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
708 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
710 Log_OC
.d(TAG
, "onSaveInstanceState() end");
716 protected void onResume() {
718 Log_OC
.e(TAG
, "onResume() start");
720 // refresh list of files
721 refreshListOfFilesFragment();
723 // Listen for sync messages
724 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
725 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
726 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
727 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
728 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
729 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
730 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
731 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
733 // Listen for upload messages
734 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
735 mUploadFinishReceiver
= new UploadFinishReceiver();
736 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
738 // Listen for download messages
739 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
740 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
741 mDownloadFinishReceiver
= new DownloadFinishReceiver();
742 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
744 Log_OC
.d(TAG
, "onResume() end");
749 protected void onPause() {
750 Log_OC
.e(TAG
, "onPause() start");
751 if (mSyncBroadcastReceiver
!= null
) {
752 unregisterReceiver(mSyncBroadcastReceiver
);
753 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
754 mSyncBroadcastReceiver
= null
;
756 if (mUploadFinishReceiver
!= null
) {
757 unregisterReceiver(mUploadFinishReceiver
);
758 mUploadFinishReceiver
= null
;
760 if (mDownloadFinishReceiver
!= null
) {
761 unregisterReceiver(mDownloadFinishReceiver
);
762 mDownloadFinishReceiver
= null
;
766 Log_OC
.d(TAG
, "onPause() end");
772 protected Dialog
onCreateDialog(int id
) {
773 Dialog dialog
= null
;
774 AlertDialog
.Builder builder
;
776 case DIALOG_SHORT_WAIT
: {
777 ProgressDialog working_dialog
= new ProgressDialog(this);
778 working_dialog
.setMessage(getResources().getString(
779 R
.string
.wait_a_moment
));
780 working_dialog
.setIndeterminate(true
);
781 working_dialog
.setCancelable(false
);
782 dialog
= working_dialog
;
785 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
788 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
789 getString(R
.string
.actionbar_upload_from_apps
) };
791 builder
= new AlertDialog
.Builder(this);
792 builder
.setTitle(R
.string
.actionbar_upload
);
793 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
794 public void onClick(DialogInterface dialog
, int item
) {
797 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
798 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
799 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
801 // TODO create and handle new fragment
802 // LocalFileListFragment
804 } else if (item
== 1) {
805 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
806 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
807 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
808 ACTION_SELECT_CONTENT_FROM_APPS
);
812 dialog
= builder
.create();
815 case DIALOG_CERT_NOT_SAVED
: {
816 builder
= new AlertDialog
.Builder(this);
817 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
818 builder
.setCancelable(false
);
819 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
821 public void onClick(DialogInterface dialog
, int which
) {
825 dialog
= builder
.create();
837 * Translates a content URI of an image to a physical path
839 * @param uri The URI to resolve
840 * @return The path to the image or null if it could not be found
842 public String
getPath(Uri uri
) {
843 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
844 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
845 if (cursor
!= null
) {
846 int column_index
= cursor
847 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
848 cursor
.moveToFirst();
849 return cursor
.getString(column_index
);
855 * Pushes a directory to the drop down list
856 * @param directory to push
857 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
859 public void pushDirname(OCFile directory
) {
860 if(!directory
.isFolder()){
861 throw new IllegalArgumentException("Only directories may be pushed!");
863 mDirectories
.insert(directory
.getFileName(), 0);
868 * Pops a directory name from the drop down list
869 * @return True, unless the stack is empty
871 public boolean popDirname() {
872 mDirectories
.remove(mDirectories
.getItem(0));
873 return !mDirectories
.isEmpty();
876 // Custom array adapter to override text colors
877 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
879 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
883 public View
getView(int position
, View convertView
, ViewGroup parent
) {
884 View v
= super.getView(position
, convertView
, parent
);
886 ((TextView
) v
).setTextColor(getResources().getColorStateList(
887 android
.R
.color
.white
));
889 fixRoot((TextView
) v
);
893 public View
getDropDownView(int position
, View convertView
,
895 View v
= super.getDropDownView(position
, convertView
, parent
);
897 ((TextView
) v
).setTextColor(getResources().getColorStateList(
898 android
.R
.color
.white
));
900 fixRoot((TextView
) v
);
904 private void fixRoot(TextView v
) {
905 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
906 v
.setText(R
.string
.default_display_name_for_root_folder
);
912 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
915 * {@link BroadcastReceiver} to enable syncing feedback in UI
918 public void onReceive(Context context
, Intent intent
) {
920 String event
= intent
.getAction();
921 Log_OC
.d(TAG
, "Received broadcast " + event
);
922 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
923 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
924 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
925 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
929 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
930 mSyncInProgress
= true
;
933 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
934 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
936 if (currentDir
== null
) {
937 // current folder was removed from the server
938 Toast
.makeText( FileDisplayActivity
.this,
939 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
945 if (currentFile
== null
&& !getFile().isFolder()) {
946 // currently selected file was removed in the server, and now we know it
947 cleanSecondFragment();
948 currentFile
= currentDir
;
951 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
952 OCFileListFragment fileListFragment
= getListOfFilesFragment();
953 if (fileListFragment
!= null
) {
954 fileListFragment
.listDirectory(currentDir
);
957 setFile(currentFile
);
960 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
962 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
964 /// TODO refactor and make common
965 synchResult
!= null
&& !synchResult
.isSuccess() &&
966 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
967 synchResult
.isIdPRedirection() ||
968 (synchResult
.isException() && synchResult
.getException()
969 instanceof AuthenticatorException
))) {
971 OwnCloudClient client
= null
;
973 OwnCloudAccount ocAccount
=
974 new OwnCloudAccount(getAccount(), context
);
975 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
976 removeClientFor(ocAccount
));
977 // TODO get rid of these exceptions
978 } catch (AccountNotFoundException e
) {
980 } catch (AuthenticatorException e
) {
982 } catch (OperationCanceledException e
) {
984 } catch (IOException e
) {
988 if (client
!= null
) {
989 OwnCloudCredentials cred
= client
.getCredentials();
991 AccountManager am
= AccountManager
.get(context
);
992 if (cred
.authTokenExpires()) {
993 am
.invalidateAuthToken(
998 am
.clearPassword(getAccount());
1003 requestCredentialsUpdate();
1007 removeStickyBroadcast(intent
);
1008 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1009 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1011 setBackgroundText();
1015 if (synchResult
!= null
) {
1016 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1017 mLastSslUntrustedServerResult
= synchResult
;
1020 } catch (RuntimeException e
) {
1021 // avoid app crashes after changing the serial id of RemoteOperationResult
1022 // in owncloud library with broadcast notifications pending to process
1023 removeStickyBroadcast(intent
);
1029 * Show a text message on screen view for notifying user if content is
1030 * loading or folder is empty
1032 private void setBackgroundText() {
1033 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1034 if (ocFileListFragment
!= null
) {
1035 int message
= R
.string
.file_list_loading
;
1036 if (!mSyncInProgress
) {
1037 // In case file list is empty
1038 message
= R
.string
.file_list_empty
;
1040 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1042 Log_OC
.e(TAG
, "OCFileListFragment is null");
1047 * Once the file upload has finished -> update view
1049 private class UploadFinishReceiver
extends BroadcastReceiver
{
1051 * Once the file upload has finished -> update view
1052 * @author David A. Velasco
1053 * {@link BroadcastReceiver} to enable upload feedback in UI
1056 public void onReceive(Context context
, Intent intent
) {
1058 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1059 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1060 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1061 OCFile currentDir
= getCurrentDir();
1062 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1063 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1065 if (sameAccount
&& isDescendant
) {
1066 refreshListOfFilesFragment();
1069 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1070 boolean renamedInUpload
= getFile().getRemotePath().
1071 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1072 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1074 FileFragment details
= getSecondFragment();
1075 boolean detailFragmentIsShown
= (details
!= null
&&
1076 details
instanceof FileDetailFragment
);
1078 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1079 if (uploadWasFine
) {
1080 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1082 if (renamedInUpload
) {
1083 String newName
= (new File(uploadedRemotePath
)).getName();
1084 Toast msg
= Toast
.makeText(
1087 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1092 if (uploadWasFine
|| getFile().fileExists()) {
1093 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1095 cleanSecondFragment();
1098 // Force the preview if the file is an image
1099 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1100 startImagePreview(getFile());
1101 } // TODO what about other kind of previews?
1105 if (intent
!= null
) {
1106 removeStickyBroadcast(intent
);
1116 * Class waiting for broadcast events from the {@link FielDownloader} service.
1118 * Updates the UI when a download is started or finished, provided that it is relevant for the
1121 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1123 public void onReceive(Context context
, Intent intent
) {
1125 boolean sameAccount
= isSameAccount(context
, intent
);
1126 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1127 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1129 if (sameAccount
&& isDescendant
) {
1130 refreshListOfFilesFragment();
1131 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1134 if (mWaitingToSend
!= null
) {
1135 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1136 if (mWaitingToSend
.isDown()) {
1137 sendDownloadedFile();
1142 if (intent
!= null
) {
1143 removeStickyBroadcast(intent
);
1148 private boolean isDescendant(String downloadedRemotePath
) {
1149 OCFile currentDir
= getCurrentDir();
1150 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1153 private boolean isSameAccount(Context context
, Intent intent
) {
1154 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1155 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1160 public void browseToRoot() {
1161 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1162 if (listOfFiles
!= null
) { // should never be null, indeed
1163 while (mDirectories
.getCount() > 1) {
1166 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1167 listOfFiles
.listDirectory(root
);
1168 setFile(listOfFiles
.getCurrentFile());
1169 startSyncFolderOperation(root
, false
);
1171 cleanSecondFragment();
1175 public void browseTo(OCFile folder
) {
1176 if (folder
== null
|| !folder
.isFolder()) {
1177 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1179 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1180 if (listOfFiles
!= null
) {
1181 setNavigationListWithFolder(folder
);
1182 listOfFiles
.listDirectory(folder
);
1183 setFile(listOfFiles
.getCurrentFile());
1184 startSyncFolderOperation(folder
, false
);
1186 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1188 cleanSecondFragment();
1195 * Updates action bar and second fragment, if in dual pane mode.
1198 public void onBrowsedDownTo(OCFile directory
) {
1199 pushDirname(directory
);
1200 cleanSecondFragment();
1203 startSyncFolderOperation(directory
, false
);
1208 * Shows the information of the {@link OCFile} received as a
1209 * parameter in the second fragment.
1211 * @param file {@link OCFile} whose details will be shown
1214 public void showDetails(OCFile file
) {
1215 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1216 setSecondFragment(detailFragment
);
1217 updateFragmentsVisibility(true
);
1218 updateNavigationElementsInActionBar(file
);
1226 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1227 ActionBar actionBar
= getSupportActionBar();
1228 if (chosenFile
== null
|| mDualPane
) {
1229 // only list of files - set for browsing through folders
1230 OCFile currentDir
= getCurrentDir();
1231 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1232 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1233 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1235 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1237 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1238 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1241 actionBar
.setDisplayHomeAsUpEnabled(true
);
1242 actionBar
.setDisplayShowTitleEnabled(true
);
1243 actionBar
.setTitle(chosenFile
.getFileName());
1244 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1250 protected ServiceConnection
newTransferenceServiceConnection() {
1251 return new ListServiceConnection();
1254 /** Defines callbacks for service binding, passed to bindService() */
1255 private class ListServiceConnection
implements ServiceConnection
{
1258 public void onServiceConnected(ComponentName component
, IBinder service
) {
1259 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1260 Log_OC
.d(TAG
, "Download service connected");
1261 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1262 if (mWaitingToPreview
!= null
)
1263 if (getStorageManager() != null
) {
1264 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1265 if (!mWaitingToPreview
.isDown()) {
1266 requestForDownload();
1270 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1271 Log_OC
.d(TAG
, "Upload service connected");
1272 mUploaderBinder
= (FileUploaderBinder
) service
;
1276 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1277 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1278 if (listOfFiles
!= null
) {
1279 listOfFiles
.listDirectory();
1281 FileFragment secondFragment
= getSecondFragment();
1282 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1283 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1284 detailFragment
.listenForTransferProgress();
1285 detailFragment
.updateFileDetails(false
, false
);
1290 public void onServiceDisconnected(ComponentName component
) {
1291 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1292 Log_OC
.d(TAG
, "Download service disconnected");
1293 mDownloaderBinder
= null
;
1294 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1295 Log_OC
.d(TAG
, "Upload service disconnected");
1296 mUploaderBinder
= null
;
1304 * Launch an intent to request the PIN code to the user before letting him use the app
1306 private void requestPinCode() {
1307 boolean pinStart
= false
;
1308 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1309 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1311 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1312 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1319 public void onSavedCertificate() {
1320 startSyncFolderOperation(getCurrentDir(), false
);
1325 public void onFailedSavingCertificate() {
1326 showDialog(DIALOG_CERT_NOT_SAVED
);
1330 public void onCancelCertificate() {
1335 * Updates the view associated to the activity after the finish of some operation over files
1336 * in the current account.
1338 * @param operation Removal operation performed.
1339 * @param result Result of the removal.
1342 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1343 super.onRemoteOperationFinish(operation
, result
);
1345 if (operation
instanceof RemoveFileOperation
) {
1346 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1348 } else if (operation
instanceof RenameFileOperation
) {
1349 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1351 } else if (operation
instanceof SynchronizeFileOperation
) {
1352 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1354 } else if (operation
instanceof CreateFolderOperation
) {
1355 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1357 } else if (operation
instanceof CreateShareOperation
) {
1358 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1360 } else if (operation
instanceof UnshareLinkOperation
) {
1361 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1363 } else if (operation
instanceof MoveFileOperation
) {
1364 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1370 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1371 if (result
.isSuccess()) {
1372 refreshShowDetails();
1373 refreshListOfFilesFragment();
1378 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1379 if (result
.isSuccess()) {
1380 refreshShowDetails();
1381 refreshListOfFilesFragment();
1383 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1384 cleanSecondFragment();
1385 refreshListOfFilesFragment();
1389 private void refreshShowDetails() {
1390 FileFragment details
= getSecondFragment();
1391 if (details
!= null
) {
1392 OCFile file
= details
.getFile();
1394 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1395 if (details
instanceof PreviewMediaFragment
) {
1396 // Refresh OCFile of the fragment
1397 ((PreviewMediaFragment
) details
).updateFile(file
);
1402 invalidateOptionsMenu();
1407 * Updates the view associated to the activity after the finish of an operation trying to remove a
1410 * @param operation Removal operation performed.
1411 * @param result Result of the removal.
1413 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1414 dismissLoadingDialog();
1416 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1420 if (result
.isSuccess()) {
1421 OCFile removedFile
= operation
.getFile();
1422 FileFragment second
= getSecondFragment();
1423 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1424 if (second
instanceof PreviewMediaFragment
) {
1425 ((PreviewMediaFragment
)second
).stopPreview(true
);
1427 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1428 cleanSecondFragment();
1430 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1431 refreshListOfFilesFragment();
1433 invalidateOptionsMenu();
1435 if (result
.isSslRecoverableException()) {
1436 mLastSslUntrustedServerResult
= result
;
1437 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1444 * Updates the view associated to the activity after the finish of an operation trying to move a
1447 * @param operation Move operation performed.
1448 * @param result Result of the move operation.
1450 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1451 if (result
.isSuccess()) {
1452 dismissLoadingDialog();
1453 refreshListOfFilesFragment();
1455 dismissLoadingDialog();
1457 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1458 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1462 } catch (NotFoundException e
) {
1463 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1470 * Updates the view associated to the activity after the finish of an operation trying to rename a
1473 * @param operation Renaming operation performed.
1474 * @param result Result of the renaming.
1476 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1477 dismissLoadingDialog();
1478 OCFile renamedFile
= operation
.getFile();
1479 if (result
.isSuccess()) {
1480 FileFragment details
= getSecondFragment();
1481 if (details
!= null
) {
1482 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1483 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1484 showDetails(renamedFile
);
1486 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1487 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1488 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1489 int position
= ((PreviewMediaFragment
)details
).getPosition();
1490 startMediaPreview(renamedFile
, position
, true
);
1492 getFileOperationsHelper().openFile(renamedFile
);
1497 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1498 refreshListOfFilesFragment();
1502 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1506 if (result
.isSslRecoverableException()) {
1507 mLastSslUntrustedServerResult
= result
;
1508 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1513 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1514 dismissLoadingDialog();
1515 OCFile syncedFile
= operation
.getLocalFile();
1516 if (!result
.isSuccess()) {
1517 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1518 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1519 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1520 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1526 if (operation
.transferWasRequested()) {
1527 onTransferStateChanged(syncedFile
, true
, true
);
1530 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1538 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1540 * @param operation Creation operation performed.
1541 * @param result Result of the creation.
1543 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1544 if (result
.isSuccess()) {
1545 dismissLoadingDialog();
1546 refreshListOfFilesFragment();
1548 dismissLoadingDialog();
1550 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1551 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1555 } catch (NotFoundException e
) {
1556 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1566 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1567 refreshListOfFilesFragment();
1568 FileFragment details
= getSecondFragment();
1569 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1570 if (downloading
|| uploading
) {
1571 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1573 if (!file
.fileExists()) {
1574 cleanSecondFragment();
1576 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1584 private void requestForDownload() {
1585 Account account
= getAccount();
1586 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1587 Intent i
= new Intent(this, FileDownloader
.class);
1588 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1589 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1595 private OCFile
getCurrentDir() {
1596 OCFile file
= getFile();
1598 if (file
.isFolder()) {
1600 } else if (getStorageManager() != null
) {
1601 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1602 return getStorageManager().getFileByPath(parentPath
);
1608 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1609 long currentSyncTime
= System
.currentTimeMillis();
1611 mSyncInProgress
= true
;
1613 // perform folder synchronization
1614 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1617 getFileOperationsHelper().isSharedSupported(),
1619 getStorageManager(),
1621 getApplicationContext()
1623 synchFolderOp
.execute(getAccount(), this, null
, null
);
1625 setSupportProgressBarIndeterminateVisibility(true
);
1627 setBackgroundText();
1631 * Show untrusted cert dialog
1633 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1634 // Show a dialog with the certificate info
1635 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1636 FragmentManager fm
= getSupportFragmentManager();
1637 FragmentTransaction ft
= fm
.beginTransaction();
1638 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1641 private void requestForDownload(OCFile file
) {
1642 Account account
= getAccount();
1643 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1644 Intent i
= new Intent(this, FileDownloader
.class);
1645 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1646 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1651 private void sendDownloadedFile(){
1652 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1653 mWaitingToSend
= null
;
1658 * Requests the download of the received {@link OCFile} , updates the UI
1659 * to monitor the download progress and prepares the activity to send the file
1660 * when the download finishes.
1662 * @param file {@link OCFile} to download and preview.
1664 public void startDownloadForSending(OCFile file
) {
1665 mWaitingToSend
= file
;
1666 requestForDownload(mWaitingToSend
);
1667 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1668 updateFragmentsVisibility(hasSecondFragment
);
1672 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1674 * @param file Image {@link OCFile} to show.
1676 public void startImagePreview(OCFile file
) {
1677 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1678 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1679 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1680 startActivity(showDetailsIntent
);
1685 * Stars the preview of an already down media {@link OCFile}.
1687 * @param file Media {@link OCFile} to preview.
1688 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1689 * @param autoplay When 'true', the playback will start without user interactions.
1691 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1692 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1693 setSecondFragment(mediaFragment
);
1694 updateFragmentsVisibility(true
);
1695 updateNavigationElementsInActionBar(file
);
1700 * Requests the download of the received {@link OCFile} , updates the UI
1701 * to monitor the download progress and prepares the activity to preview
1702 * or open the file when the download finishes.
1704 * @param file {@link OCFile} to download and preview.
1706 public void startDownloadForPreview(OCFile file
) {
1707 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1708 setSecondFragment(detailFragment
);
1709 mWaitingToPreview
= file
;
1710 requestForDownload();
1711 updateFragmentsVisibility(true
);
1712 updateNavigationElementsInActionBar(file
);
1717 public void cancelTransference(OCFile file
) {
1718 getFileOperationsHelper().cancelTransference(file
);
1719 if (mWaitingToPreview
!= null
&&
1720 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1721 mWaitingToPreview
= null
;
1723 if (mWaitingToSend
!= null
&&
1724 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1725 mWaitingToSend
= null
;
1727 onTransferStateChanged(file
, false
, false
);
1731 public void onRefresh(boolean ignoreETag
) {
1732 refreshList(ignoreETag
);
1736 public void onRefresh() {
1740 private void refreshList(boolean ignoreETag
) {
1741 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1742 if (listOfFiles
!= null
) {
1743 OCFile folder
= listOfFiles
.getCurrentFile();
1744 if (folder
!= null
) {
1745 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1746 listDirectory(mFile);*/
1747 startSyncFolderOperation(folder
, ignoreETag
);