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 org
.apache
.commons
.httpclient
.methods
.PostMethod
;
26 import android
.accounts
.Account
;
27 import android
.accounts
.AccountManager
;
28 import android
.accounts
.AuthenticatorException
;
29 import android
.accounts
.OperationCanceledException
;
30 import android
.app
.AlertDialog
;
31 import android
.app
.Dialog
;
32 import android
.app
.ProgressDialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ComponentName
;
35 import android
.content
.ContentResolver
;
36 import android
.content
.Context
;
37 import android
.content
.DialogInterface
;
38 import android
.content
.Intent
;
39 import android
.content
.IntentFilter
;
40 import android
.content
.ServiceConnection
;
41 import android
.content
.SharedPreferences
;
42 import android
.content
.SyncRequest
;
43 import android
.content
.res
.Resources
.NotFoundException
;
44 import android
.database
.Cursor
;
45 import android
.net
.Uri
;
46 import android
.os
.Bundle
;
47 import android
.os
.IBinder
;
48 import android
.preference
.PreferenceManager
;
49 import android
.provider
.MediaStore
;
50 import android
.support
.v4
.app
.Fragment
;
51 import android
.support
.v4
.app
.FragmentManager
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.support
.v4
.widget
.SwipeRefreshLayout
;
54 import android
.util
.Log
;
55 import android
.view
.View
;
56 import android
.view
.ViewGroup
;
57 import android
.widget
.ArrayAdapter
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.ActionBar
;
62 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
63 import com
.actionbarsherlock
.view
.Menu
;
64 import com
.actionbarsherlock
.view
.MenuInflater
;
65 import com
.actionbarsherlock
.view
.MenuItem
;
66 import com
.actionbarsherlock
.view
.Window
;
67 import com
.owncloud
.android
.MainApp
;
68 import com
.owncloud
.android
.R
;
69 import com
.owncloud
.android
.datamodel
.OCFile
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
78 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
79 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
84 import com
.owncloud
.android
.operations
.CreateShareOperation
;
85 import com
.owncloud
.android
.operations
.MoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RenameFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
89 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
90 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
91 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
92 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
93 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
96 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
103 import com
.owncloud
.android
.utils
.DisplayUtils
;
104 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
105 import com
.owncloud
.android
.utils
.Log_OC
;
109 * Displays, what files the user has available in his ownCloud.
111 * @author Bartek Przybylski
112 * @author David A. Velasco
115 public class FileDisplayActivity
extends HookActivity
implements
116 FileFragment
.ContainerActivity
, OnNavigationListener
,
117 OnSslUntrustedCertListener
, SwipeRefreshLayout
.OnRefreshListener
{
119 private ArrayAdapter
<String
> mDirectories
;
121 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
122 private UploadFinishReceiver mUploadFinishReceiver
;
123 private DownloadFinishReceiver mDownloadFinishReceiver
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
126 private boolean mDualPane
;
127 private View mLeftFragmentContainer
;
128 private View mRightFragmentContainer
;
130 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
131 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
132 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
134 public static final int DIALOG_SHORT_WAIT
= 0;
135 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
136 private static final int DIALOG_CERT_NOT_SAVED
= 2;
138 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
140 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
141 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
142 public static final int ACTION_MOVE_FILES
= 3;
144 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
146 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
147 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
149 private OCFile mWaitingToPreview
;
151 private boolean mSyncInProgress
= false
;
153 private String DIALOG_UNTRUSTED_CERT
;
155 private OCFile mWaitingToSend
;
157 private Integer sortItemChecked
= 0;
160 protected void onCreate(Bundle savedInstanceState
) {
161 Log_OC
.d(TAG
, "onCreate() start");
162 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
164 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
166 // PIN CODE request ; best location is to decide, let's try this first
167 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
169 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
173 /// grant that FileObserverService is watching favourite files
174 if (savedInstanceState
== null
) {
175 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
176 startService(initObserversIntent
);
179 /// Load of saved instance state
180 if(savedInstanceState
!= null
) {
181 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
182 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
183 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
186 mWaitingToPreview
= null
;
187 mSyncInProgress
= false
;
188 mWaitingToSend
= null
;
193 // Inflate and set the layout view
194 setContentView(R
.layout
.files
);
195 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
196 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
197 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
198 if (savedInstanceState
== null
) {
199 createMinFragments();
203 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
204 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
205 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
209 Log_OC
.d(TAG
, "onCreate() end");
213 protected void onStart() {
215 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
219 protected void onDestroy() {
224 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
227 protected void onAccountSet(boolean stateWasRecovered
) {
228 super.onAccountSet(stateWasRecovered
);
229 if (getAccount() != null
) {
230 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
231 OCFile file
= getFile();
232 // get parent from path
233 String parentPath
= "";
235 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
236 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
237 // get parent from path
238 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
239 if (getStorageManager().getFileByPath(parentPath
) == null
)
240 file
= null
; // not able to know the directory where the file is uploading
242 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
246 // fall back to root folder
247 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
250 setNavigationListWithFolder(file
);
252 if (!stateWasRecovered
) {
253 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
254 initFragmentsWithFile();
255 if (file
.isFolder()) {
256 startSyncFolderOperation(file
);
260 updateFragmentsVisibility(!file
.isFolder());
261 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
267 private void setNavigationListWithFolder(OCFile file
) {
268 mDirectories
.clear();
269 OCFile fileIt
= file
;
271 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
272 if (fileIt
.isFolder()) {
273 mDirectories
.add(fileIt
.getFileName());
275 // get parent from path
276 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
277 fileIt
= getStorageManager().getFileByPath(parentPath
);
279 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
283 private void createMinFragments() {
284 OCFileListFragment listOfFiles
= new OCFileListFragment();
285 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
286 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
287 transaction
.commit();
290 private void initFragmentsWithFile() {
291 if (getAccount() != null
&& getFile() != null
) {
293 OCFileListFragment listOfFiles
= getListOfFilesFragment();
294 if (listOfFiles
!= null
) {
295 listOfFiles
.listDirectory(getCurrentDir());
297 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
301 OCFile file
= getFile();
302 Fragment secondFragment
= chooseInitialSecondFragment(file
);
303 if (secondFragment
!= null
) {
304 setSecondFragment(secondFragment
);
305 updateFragmentsVisibility(true
);
306 updateNavigationElementsInActionBar(file
);
309 cleanSecondFragment();
313 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
314 if (getAccount() == null
) {
315 Log
.wtf(TAG
, "\t account is NULL");
317 if (getFile() == null
) {
318 Log
.wtf(TAG
, "\t file is NULL");
323 private Fragment
chooseInitialSecondFragment(OCFile file
) {
324 Fragment secondFragment
= null
;
325 if (file
!= null
&& !file
.isFolder()) {
326 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
327 && file
.getLastSyncDateForProperties() > 0 // temporal fix
329 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
330 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
331 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
334 secondFragment
= new FileDetailFragment(file
, getAccount());
337 return secondFragment
;
342 * Replaces the second fragment managed by the activity with the received as
345 * Assumes never will be more than two fragments managed at the same time.
347 * @param fragment New second Fragment to set.
349 private void setSecondFragment(Fragment fragment
) {
350 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
351 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
352 transaction
.commit();
356 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
358 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
359 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
361 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
362 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
365 } else if (existsSecondFragment
) {
366 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
367 mLeftFragmentContainer
.setVisibility(View
.GONE
);
369 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
374 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
377 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
378 mRightFragmentContainer
.setVisibility(View
.GONE
);
384 private OCFileListFragment
getListOfFilesFragment() {
385 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
386 if (listOfFiles
!= null
) {
387 return (OCFileListFragment
)listOfFiles
;
389 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
393 public FileFragment
getSecondFragment() {
394 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
395 if (second
!= null
) {
396 return (FileFragment
)second
;
401 protected void cleanSecondFragment() {
402 Fragment second
= getSecondFragment();
403 if (second
!= null
) {
404 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
408 updateFragmentsVisibility(false
);
409 updateNavigationElementsInActionBar(null
);
412 protected void refreshListOfFilesFragment() {
413 OCFileListFragment fileListFragment
= getListOfFilesFragment();
414 if (fileListFragment
!= null
) {
415 fileListFragment
.listDirectory();
419 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
420 FileFragment secondFragment
= getSecondFragment();
421 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
422 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
423 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
424 OCFile fileInFragment
= detailsFragment
.getFile();
425 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
426 // the user browsed to other file ; forget the automatic preview
427 mWaitingToPreview
= null
;
429 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
430 // grant that the right panel updates the progress bar
431 detailsFragment
.listenForTransferProgress();
432 detailsFragment
.updateFileDetails(true
, false
);
434 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
435 // update the right panel
436 boolean detailsFragmentChanged
= false
;
439 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
440 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
441 startMediaPreview(mWaitingToPreview
, 0, true
);
442 detailsFragmentChanged
= true
;
444 getFileOperationsHelper().openFile(mWaitingToPreview
);
447 mWaitingToPreview
= null
;
449 if (!detailsFragmentChanged
) {
450 detailsFragment
.updateFileDetails(false
, (success
));
457 public boolean onCreateOptionsMenu(Menu menu
) {
458 MenuInflater inflater
= getSherlock().getMenuInflater();
459 inflater
.inflate(R
.menu
.main_menu
, menu
);
464 public boolean onOptionsItemSelected(MenuItem item
) {
465 boolean retval
= true
;
466 switch (item
.getItemId()) {
467 case R
.id
.action_create_dir
: {
468 CreateFolderDialogFragment dialog
=
469 CreateFolderDialogFragment
.newInstance(getCurrentDir());
470 dialog
.show(getSupportFragmentManager(), "createdirdialog");
473 case R
.id
.action_sync_account
: {
474 startSynchronization();
477 case R
.id
.action_upload
: {
478 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
481 case R
.id
.action_settings
: {
482 Intent settingsIntent
= new Intent(this, Preferences
.class);
483 startActivity(settingsIntent
);
486 case android
.R
.id
.home
: {
487 FileFragment second
= getSecondFragment();
488 OCFile currentDir
= getCurrentDir();
489 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
490 (second
!= null
&& second
.getFile() != null
)) {
496 case R
.id
.action_sort
: {
497 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
498 builder
.setTitle(R
.string
.actionbar_sort_title
)
499 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortItemChecked
, new DialogInterface
.OnClickListener() {
500 public void onClick(DialogInterface dialog
, int which
) {
501 sortItemChecked
= which
;
519 builder
.create().show();
523 retval
= super.onOptionsItemSelected(item
);
528 private void startSynchronization() {
529 Log_OC
.e(TAG
, "Got to start sync");
530 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
531 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
532 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
533 Bundle bundle
= new Bundle();
534 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
535 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
536 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
537 ContentResolver
.requestSync(
539 MainApp
.getAuthority(), bundle
);
541 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
542 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
543 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
544 builder
.setExpedited(true
);
545 builder
.setManual(true
);
547 SyncRequest request
= builder
.build();
548 ContentResolver
.requestSync(request
);
554 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
555 if (itemPosition
!= 0) {
556 String targetPath
= "";
557 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
558 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
560 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
561 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
562 if (targetFolder
!= null
) {
563 browseTo(targetFolder
);
566 // the next operation triggers a new call to this method, but it's necessary to
567 // ensure that the name exposed in the action bar is the current directory when the
568 // user selected it in the navigation list
569 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
570 getSupportActionBar().setSelectedNavigationItem(0);
576 * Called, when the user selected something for uploading
578 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
579 super.onActivityResult(requestCode
, resultCode
, data
);
581 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
582 requestSimpleUpload(data
, resultCode
);
584 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
585 requestMultipleUpload(data
, resultCode
);
587 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
588 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
590 final Intent fData
= data
;
591 final int fResultCode
= resultCode
;
592 getHandler().postDelayed(
596 requestMoveOperation(fData
, fResultCode
);
599 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
604 private void requestMultipleUpload(Intent data
, int resultCode
) {
605 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
606 if (filePaths
!= null
) {
607 String
[] remotePaths
= new String
[filePaths
.length
];
608 String remotePathBase
= "";
609 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
610 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
612 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
613 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
614 for (int j
= 0; j
< remotePaths
.length
; j
++) {
615 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
618 Intent i
= new Intent(this, FileUploader
.class);
619 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
620 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
621 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
622 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
623 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
624 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
628 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
629 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
636 private void requestSimpleUpload(Intent data
, int resultCode
) {
637 String filepath
= null
;
639 Uri selectedImageUri
= data
.getData();
641 String filemanagerstring
= selectedImageUri
.getPath();
642 String selectedImagePath
= getPath(selectedImageUri
);
644 if (selectedImagePath
!= null
)
645 filepath
= selectedImagePath
;
647 filepath
= filemanagerstring
;
649 } catch (Exception e
) {
650 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
654 if (filepath
== null
) {
655 Log_OC
.e(TAG
, "Couldnt resolve path to file");
656 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
662 Intent i
= new Intent(this, FileUploader
.class);
663 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
665 String remotepath
= new String();
666 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
667 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
669 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
670 remotepath
+= OCFile
.PATH_SEPARATOR
;
671 remotepath
+= new File(filepath
).getName();
673 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
674 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
675 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
676 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
677 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
682 * Request the operation for moving the file/folder from one path to another
684 * @param data Intent received
685 * @param resultCode Result code received
687 private void requestMoveOperation(Intent data
, int resultCode
) {
688 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
689 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
690 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
694 public void onBackPressed() {
695 OCFileListFragment listOfFiles
= getListOfFilesFragment();
696 if (mDualPane
|| getSecondFragment() == null
) {
697 if (listOfFiles
!= null
) { // should never be null, indeed
698 if (mDirectories
.getCount() <= 1) {
702 int levelsUp
= listOfFiles
.onBrowseUp();
703 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
708 if (listOfFiles
!= null
) { // should never be null, indeed
709 setFile(listOfFiles
.getCurrentFile());
711 cleanSecondFragment();
716 protected void onSaveInstanceState(Bundle outState
) {
717 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
718 Log_OC
.e(TAG
, "onSaveInstanceState() start");
719 super.onSaveInstanceState(outState
);
720 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
721 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
722 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
723 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
725 Log_OC
.d(TAG
, "onSaveInstanceState() end");
731 protected void onResume() {
733 Log_OC
.e(TAG
, "onResume() start");
735 // refresh list of files
736 refreshListOfFilesFragment();
738 // Listen for sync messages
739 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
740 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
741 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
742 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
743 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
744 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
745 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
746 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
748 // Listen for upload messages
749 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
750 mUploadFinishReceiver
= new UploadFinishReceiver();
751 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
753 // Listen for download messages
754 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
755 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
756 mDownloadFinishReceiver
= new DownloadFinishReceiver();
757 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
759 Log_OC
.d(TAG
, "onResume() end");
764 protected void onPause() {
765 Log_OC
.e(TAG
, "onPause() start");
766 if (mSyncBroadcastReceiver
!= null
) {
767 unregisterReceiver(mSyncBroadcastReceiver
);
768 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
769 mSyncBroadcastReceiver
= null
;
771 if (mUploadFinishReceiver
!= null
) {
772 unregisterReceiver(mUploadFinishReceiver
);
773 mUploadFinishReceiver
= null
;
775 if (mDownloadFinishReceiver
!= null
) {
776 unregisterReceiver(mDownloadFinishReceiver
);
777 mDownloadFinishReceiver
= null
;
781 Log_OC
.d(TAG
, "onPause() end");
787 protected Dialog
onCreateDialog(int id
) {
788 Dialog dialog
= null
;
789 AlertDialog
.Builder builder
;
791 case DIALOG_SHORT_WAIT
: {
792 ProgressDialog working_dialog
= new ProgressDialog(this);
793 working_dialog
.setMessage(getResources().getString(
794 R
.string
.wait_a_moment
));
795 working_dialog
.setIndeterminate(true
);
796 working_dialog
.setCancelable(false
);
797 dialog
= working_dialog
;
800 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
803 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
804 getString(R
.string
.actionbar_upload_from_apps
) };
806 builder
= new AlertDialog
.Builder(this);
807 builder
.setTitle(R
.string
.actionbar_upload
);
808 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
809 public void onClick(DialogInterface dialog
, int item
) {
812 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
813 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
814 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
816 // TODO create and handle new fragment
817 // LocalFileListFragment
819 } else if (item
== 1) {
820 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
821 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
822 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
823 ACTION_SELECT_CONTENT_FROM_APPS
);
827 dialog
= builder
.create();
830 case DIALOG_CERT_NOT_SAVED
: {
831 builder
= new AlertDialog
.Builder(this);
832 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
833 builder
.setCancelable(false
);
834 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
836 public void onClick(DialogInterface dialog
, int which
) {
840 dialog
= builder
.create();
852 * Translates a content URI of an image to a physical path
854 * @param uri The URI to resolve
855 * @return The path to the image or null if it could not be found
857 public String
getPath(Uri uri
) {
858 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
859 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
860 if (cursor
!= null
) {
861 int column_index
= cursor
862 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
863 cursor
.moveToFirst();
864 return cursor
.getString(column_index
);
870 * Pushes a directory to the drop down list
871 * @param directory to push
872 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
874 public void pushDirname(OCFile directory
) {
875 if(!directory
.isFolder()){
876 throw new IllegalArgumentException("Only directories may be pushed!");
878 mDirectories
.insert(directory
.getFileName(), 0);
883 * Pops a directory name from the drop down list
884 * @return True, unless the stack is empty
886 public boolean popDirname() {
887 mDirectories
.remove(mDirectories
.getItem(0));
888 return !mDirectories
.isEmpty();
891 // Custom array adapter to override text colors
892 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
894 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
898 public View
getView(int position
, View convertView
, ViewGroup parent
) {
899 View v
= super.getView(position
, convertView
, parent
);
901 ((TextView
) v
).setTextColor(getResources().getColorStateList(
902 android
.R
.color
.white
));
904 fixRoot((TextView
) v
);
908 public View
getDropDownView(int position
, View convertView
,
910 View v
= super.getDropDownView(position
, convertView
, parent
);
912 ((TextView
) v
).setTextColor(getResources().getColorStateList(
913 android
.R
.color
.white
));
915 fixRoot((TextView
) v
);
919 private void fixRoot(TextView v
) {
920 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
921 v
.setText(R
.string
.default_display_name_for_root_folder
);
927 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
930 * {@link BroadcastReceiver} to enable syncing feedback in UI
933 public void onReceive(Context context
, Intent intent
) {
935 String event
= intent
.getAction();
936 Log_OC
.d(TAG
, "Received broadcast " + event
);
937 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
938 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
939 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
940 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
944 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
945 mSyncInProgress
= true
;
948 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
949 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
951 if (currentDir
== null
) {
952 // current folder was removed from the server
953 Toast
.makeText( FileDisplayActivity
.this,
954 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
960 if (currentFile
== null
&& !getFile().isFolder()) {
961 // currently selected file was removed in the server, and now we know it
962 cleanSecondFragment();
963 currentFile
= currentDir
;
966 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
967 OCFileListFragment fileListFragment
= getListOfFilesFragment();
968 if (fileListFragment
!= null
) {
969 fileListFragment
.listDirectory(currentDir
);
972 setFile(currentFile
);
975 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
977 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
979 /// TODO refactor and make common
980 synchResult
!= null
&& !synchResult
.isSuccess() &&
981 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
982 synchResult
.isIdPRedirection() ||
983 (synchResult
.isException() && synchResult
.getException()
984 instanceof AuthenticatorException
))) {
986 OwnCloudClient client
= null
;
988 OwnCloudAccount ocAccount
=
989 new OwnCloudAccount(getAccount(), context
);
990 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
991 removeClientFor(ocAccount
));
992 // TODO get rid of these exceptions
993 } catch (AccountNotFoundException e
) {
995 } catch (AuthenticatorException e
) {
997 } catch (OperationCanceledException e
) {
999 } catch (IOException e
) {
1000 e
.printStackTrace();
1003 if (client
!= null
) {
1004 OwnCloudCredentials cred
= client
.getCredentials();
1006 AccountManager am
= AccountManager
.get(context
);
1007 if (cred
.authTokenExpires()) {
1008 am
.invalidateAuthToken(
1013 am
.clearPassword(getAccount());
1018 requestCredentialsUpdate();
1022 removeStickyBroadcast(intent
);
1023 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1024 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1026 setBackgroundText();
1030 if (synchResult
!= null
) {
1031 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1032 mLastSslUntrustedServerResult
= synchResult
;
1035 } catch (RuntimeException e
) {
1036 // avoid app crashes after changing the serial id of RemoteOperationResult
1037 // in owncloud library with broadcast notifications pending to process
1038 removeStickyBroadcast(intent
);
1044 * Show a text message on screen view for notifying user if content is
1045 * loading or folder is empty
1047 private void setBackgroundText() {
1048 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1049 if (ocFileListFragment
!= null
) {
1050 int message
= R
.string
.file_list_loading
;
1051 if (!mSyncInProgress
) {
1052 // In case file list is empty
1053 message
= R
.string
.file_list_empty
;
1055 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1057 Log
.e(TAG
, "OCFileListFragment is null");
1062 * Once the file upload has finished -> update view
1064 private class UploadFinishReceiver
extends BroadcastReceiver
{
1066 * Once the file upload has finished -> update view
1067 * @author David A. Velasco
1068 * {@link BroadcastReceiver} to enable upload feedback in UI
1071 public void onReceive(Context context
, Intent intent
) {
1073 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1074 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1075 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1076 OCFile currentDir
= getCurrentDir();
1077 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1078 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1080 if (sameAccount
&& isDescendant
) {
1081 refreshListOfFilesFragment();
1084 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1085 boolean renamedInUpload
= getFile().getRemotePath().
1086 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1087 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1089 FileFragment details
= getSecondFragment();
1090 boolean detailFragmentIsShown
= (details
!= null
&&
1091 details
instanceof FileDetailFragment
);
1093 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1094 if (uploadWasFine
) {
1095 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1097 if (renamedInUpload
) {
1098 String newName
= (new File(uploadedRemotePath
)).getName();
1099 Toast msg
= Toast
.makeText(
1102 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1107 if (uploadWasFine
|| getFile().fileExists()) {
1108 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1110 cleanSecondFragment();
1113 // Force the preview if the file is an image
1114 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1115 startImagePreview(getFile());
1116 } // TODO what about other kind of previews?
1120 if (intent
!= null
) {
1121 removeStickyBroadcast(intent
);
1131 * Class waiting for broadcast events from the {@link FielDownloader} service.
1133 * Updates the UI when a download is started or finished, provided that it is relevant for the
1136 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1138 public void onReceive(Context context
, Intent intent
) {
1140 boolean sameAccount
= isSameAccount(context
, intent
);
1141 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1142 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1144 if (sameAccount
&& isDescendant
) {
1145 refreshListOfFilesFragment();
1146 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1149 if (mWaitingToSend
!= null
) {
1150 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1151 if (mWaitingToSend
.isDown()) {
1152 sendDownloadedFile();
1157 if (intent
!= null
) {
1158 removeStickyBroadcast(intent
);
1163 private boolean isDescendant(String downloadedRemotePath
) {
1164 OCFile currentDir
= getCurrentDir();
1165 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1168 private boolean isSameAccount(Context context
, Intent intent
) {
1169 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1170 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1175 public void browseToRoot() {
1176 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1177 if (listOfFiles
!= null
) { // should never be null, indeed
1178 while (mDirectories
.getCount() > 1) {
1181 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1182 listOfFiles
.listDirectory(root
);
1183 setFile(listOfFiles
.getCurrentFile());
1184 startSyncFolderOperation(root
);
1186 cleanSecondFragment();
1190 public void browseTo(OCFile folder
) {
1191 if (folder
== null
|| !folder
.isFolder()) {
1192 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1194 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1195 if (listOfFiles
!= null
) {
1196 setNavigationListWithFolder(folder
);
1197 listOfFiles
.listDirectory(folder
);
1198 setFile(listOfFiles
.getCurrentFile());
1199 startSyncFolderOperation(folder
);
1201 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1203 cleanSecondFragment();
1210 * Updates action bar and second fragment, if in dual pane mode.
1213 public void onBrowsedDownTo(OCFile directory
) {
1214 pushDirname(directory
);
1215 cleanSecondFragment();
1218 startSyncFolderOperation(directory
);
1223 * Shows the information of the {@link OCFile} received as a
1224 * parameter in the second fragment.
1226 * @param file {@link OCFile} whose details will be shown
1229 public void showDetails(OCFile file
) {
1230 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1231 setSecondFragment(detailFragment
);
1232 updateFragmentsVisibility(true
);
1233 updateNavigationElementsInActionBar(file
);
1241 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1242 ActionBar actionBar
= getSupportActionBar();
1243 if (chosenFile
== null
|| mDualPane
) {
1244 // only list of files - set for browsing through folders
1245 OCFile currentDir
= getCurrentDir();
1246 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1247 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1248 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1250 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1252 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1253 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1256 actionBar
.setDisplayHomeAsUpEnabled(true
);
1257 actionBar
.setDisplayShowTitleEnabled(true
);
1258 actionBar
.setTitle(chosenFile
.getFileName());
1259 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1265 protected ServiceConnection
newTransferenceServiceConnection() {
1266 return new ListServiceConnection();
1269 /** Defines callbacks for service binding, passed to bindService() */
1270 private class ListServiceConnection
implements ServiceConnection
{
1273 public void onServiceConnected(ComponentName component
, IBinder service
) {
1274 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1275 Log_OC
.d(TAG
, "Download service connected");
1276 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1277 if (mWaitingToPreview
!= null
)
1278 if (getStorageManager() != null
) {
1279 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1280 if (!mWaitingToPreview
.isDown()) {
1281 requestForDownload();
1285 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1286 Log_OC
.d(TAG
, "Upload service connected");
1287 mUploaderBinder
= (FileUploaderBinder
) service
;
1291 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1292 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1293 if (listOfFiles
!= null
) {
1294 listOfFiles
.listDirectory();
1296 FileFragment secondFragment
= getSecondFragment();
1297 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1298 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1299 detailFragment
.listenForTransferProgress();
1300 detailFragment
.updateFileDetails(false
, false
);
1305 public void onServiceDisconnected(ComponentName component
) {
1306 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1307 Log_OC
.d(TAG
, "Download service disconnected");
1308 mDownloaderBinder
= null
;
1309 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1310 Log_OC
.d(TAG
, "Upload service disconnected");
1311 mUploaderBinder
= null
;
1319 * Launch an intent to request the PIN code to the user before letting him use the app
1321 private void requestPinCode() {
1322 boolean pinStart
= false
;
1323 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1324 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1326 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1327 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1334 public void onSavedCertificate() {
1335 startSyncFolderOperation(getCurrentDir());
1340 public void onFailedSavingCertificate() {
1341 showDialog(DIALOG_CERT_NOT_SAVED
);
1345 public void onCancelCertificate() {
1350 * Updates the view associated to the activity after the finish of some operation over files
1351 * in the current account.
1353 * @param operation Removal operation performed.
1354 * @param result Result of the removal.
1357 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1358 super.onRemoteOperationFinish(operation
, result
);
1360 if (operation
instanceof RemoveFileOperation
) {
1361 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1363 } else if (operation
instanceof RenameFileOperation
) {
1364 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1366 } else if (operation
instanceof SynchronizeFileOperation
) {
1367 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1369 } else if (operation
instanceof CreateFolderOperation
) {
1370 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1372 } else if (operation
instanceof CreateShareOperation
) {
1373 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1375 } else if (operation
instanceof UnshareLinkOperation
) {
1376 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1378 } else if (operation
instanceof MoveFileOperation
) {
1379 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1385 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1386 if (result
.isSuccess()) {
1387 refreshShowDetails();
1388 refreshListOfFilesFragment();
1393 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1394 if (result
.isSuccess()) {
1395 refreshShowDetails();
1396 refreshListOfFilesFragment();
1398 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1399 cleanSecondFragment();
1400 refreshListOfFilesFragment();
1404 private void refreshShowDetails() {
1405 FileFragment details
= getSecondFragment();
1406 if (details
!= null
) {
1407 OCFile file
= details
.getFile();
1409 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1410 if (details
instanceof PreviewMediaFragment
) {
1411 // Refresh OCFile of the fragment
1412 ((PreviewMediaFragment
) details
).updateFile(file
);
1417 invalidateOptionsMenu();
1422 * Updates the view associated to the activity after the finish of an operation trying to remove a
1425 * @param operation Removal operation performed.
1426 * @param result Result of the removal.
1428 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1429 dismissLoadingDialog();
1431 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1435 if (result
.isSuccess()) {
1436 OCFile removedFile
= operation
.getFile();
1437 FileFragment second
= getSecondFragment();
1438 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1439 if (second
instanceof PreviewMediaFragment
) {
1440 ((PreviewMediaFragment
)second
).stopPreview(true
);
1442 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1443 cleanSecondFragment();
1445 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1446 refreshListOfFilesFragment();
1448 invalidateOptionsMenu();
1450 if (result
.isSslRecoverableException()) {
1451 mLastSslUntrustedServerResult
= result
;
1452 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1459 * Updates the view associated to the activity after the finish of an operation trying to move a
1462 * @param operation Move operation performed.
1463 * @param result Result of the move operation.
1465 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1466 if (result
.isSuccess()) {
1467 dismissLoadingDialog();
1468 refreshListOfFilesFragment();
1470 dismissLoadingDialog();
1472 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1473 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1477 } catch (NotFoundException e
) {
1478 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1485 * Updates the view associated to the activity after the finish of an operation trying to rename a
1488 * @param operation Renaming operation performed.
1489 * @param result Result of the renaming.
1491 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1492 dismissLoadingDialog();
1493 OCFile renamedFile
= operation
.getFile();
1494 if (result
.isSuccess()) {
1495 FileFragment details
= getSecondFragment();
1496 if (details
!= null
) {
1497 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1498 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1499 showDetails(renamedFile
);
1501 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1502 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1503 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1504 int position
= ((PreviewMediaFragment
)details
).getPosition();
1505 startMediaPreview(renamedFile
, position
, true
);
1507 getFileOperationsHelper().openFile(renamedFile
);
1512 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1513 refreshListOfFilesFragment();
1517 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1521 if (result
.isSslRecoverableException()) {
1522 mLastSslUntrustedServerResult
= result
;
1523 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1528 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1529 dismissLoadingDialog();
1530 OCFile syncedFile
= operation
.getLocalFile();
1531 if (!result
.isSuccess()) {
1532 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1533 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1534 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1535 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1541 if (operation
.transferWasRequested()) {
1542 onTransferStateChanged(syncedFile
, true
, true
);
1545 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1553 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1555 * @param operation Creation operation performed.
1556 * @param result Result of the creation.
1558 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1559 if (result
.isSuccess()) {
1560 dismissLoadingDialog();
1561 refreshListOfFilesFragment();
1563 dismissLoadingDialog();
1565 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1566 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1570 } catch (NotFoundException e
) {
1571 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1581 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1582 refreshListOfFilesFragment();
1583 FileFragment details
= getSecondFragment();
1584 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1585 if (downloading
|| uploading
) {
1586 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1588 if (!file
.fileExists()) {
1589 cleanSecondFragment();
1591 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1599 private void requestForDownload() {
1600 Account account
= getAccount();
1601 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1602 Intent i
= new Intent(this, FileDownloader
.class);
1603 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1604 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1610 private OCFile
getCurrentDir() {
1611 OCFile file
= getFile();
1613 if (file
.isFolder()) {
1615 } else if (getStorageManager() != null
) {
1616 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1617 return getStorageManager().getFileByPath(parentPath
);
1623 public void startSyncFolderOperation(OCFile folder
) {
1624 long currentSyncTime
= System
.currentTimeMillis();
1626 mSyncInProgress
= true
;
1628 // perform folder synchronization
1629 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1632 getFileOperationsHelper().isSharedSupported(),
1633 getStorageManager(),
1635 getApplicationContext()
1637 synchFolderOp
.execute(getAccount(), this, null
, null
);
1639 setSupportProgressBarIndeterminateVisibility(true
);
1641 setBackgroundText();
1645 * Show untrusted cert dialog
1647 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1648 // Show a dialog with the certificate info
1649 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1650 FragmentManager fm
= getSupportFragmentManager();
1651 FragmentTransaction ft
= fm
.beginTransaction();
1652 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1655 private void requestForDownload(OCFile file
) {
1656 Account account
= getAccount();
1657 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1658 Intent i
= new Intent(this, FileDownloader
.class);
1659 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1660 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1665 private void sendDownloadedFile(){
1666 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1667 mWaitingToSend
= null
;
1672 * Requests the download of the received {@link OCFile} , updates the UI
1673 * to monitor the download progress and prepares the activity to send the file
1674 * when the download finishes.
1676 * @param file {@link OCFile} to download and preview.
1678 public void startDownloadForSending(OCFile file
) {
1679 mWaitingToSend
= file
;
1680 requestForDownload(mWaitingToSend
);
1681 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1682 updateFragmentsVisibility(hasSecondFragment
);
1686 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1688 * @param file Image {@link OCFile} to show.
1690 public void startImagePreview(OCFile file
) {
1691 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1692 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1693 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1694 startActivity(showDetailsIntent
);
1699 * Stars the preview of an already down media {@link OCFile}.
1701 * @param file Media {@link OCFile} to preview.
1702 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1703 * @param autoplay When 'true', the playback will start without user interactions.
1705 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1706 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1707 setSecondFragment(mediaFragment
);
1708 updateFragmentsVisibility(true
);
1709 updateNavigationElementsInActionBar(file
);
1714 * Requests the download of the received {@link OCFile} , updates the UI
1715 * to monitor the download progress and prepares the activity to preview
1716 * or open the file when the download finishes.
1718 * @param file {@link OCFile} to download and preview.
1720 public void startDownloadForPreview(OCFile file
) {
1721 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1722 setSecondFragment(detailFragment
);
1723 mWaitingToPreview
= file
;
1724 requestForDownload();
1725 updateFragmentsVisibility(true
);
1726 updateNavigationElementsInActionBar(file
);
1731 public void cancelTransference(OCFile file
) {
1732 getFileOperationsHelper().cancelTransference(file
);
1733 if (mWaitingToPreview
!= null
&&
1734 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1735 mWaitingToPreview
= null
;
1737 if (mWaitingToSend
!= null
&&
1738 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1739 mWaitingToSend
= null
;
1741 onTransferStateChanged(file
, false
, false
);
1745 public void onRefresh() {
1746 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1747 if (listOfFiles
!= null
) {
1748 OCFile folder
= listOfFiles
.getCurrentFile();
1749 if (folder
!= null
) {
1750 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1751 listDirectory(mFile);*/
1752 startSyncFolderOperation(folder
);
1757 private void sortByDate(boolean ascending
){
1758 getListOfFilesFragment().sortByDate(ascending
);
1761 private void sortBySize(boolean ascending
){
1762 getListOfFilesFragment().sortBySize(ascending
);
1765 private void sortByName(boolean ascending
){
1766 getListOfFilesFragment().sortByName(ascending
);