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
;
21 import android
.accounts
.Account
;
22 import android
.accounts
.AccountManager
;
23 import android
.accounts
.AuthenticatorException
;
24 import android
.accounts
.OperationCanceledException
;
25 import android
.app
.AlertDialog
;
26 import android
.app
.Dialog
;
27 import android
.app
.ProgressDialog
;
28 import android
.content
.BroadcastReceiver
;
29 import android
.content
.ComponentName
;
30 import android
.content
.ContentResolver
;
31 import android
.content
.Context
;
32 import android
.content
.DialogInterface
;
33 import android
.content
.Intent
;
34 import android
.content
.IntentFilter
;
35 import android
.content
.ServiceConnection
;
36 import android
.content
.SharedPreferences
;
37 import android
.content
.SyncRequest
;
38 import android
.content
.res
.Resources
.NotFoundException
;
39 import android
.database
.Cursor
;
40 import android
.net
.Uri
;
41 import android
.os
.Bundle
;
42 import android
.os
.IBinder
;
43 import android
.preference
.PreferenceManager
;
44 import android
.provider
.MediaStore
;
45 import android
.support
.v4
.app
.Fragment
;
46 import android
.support
.v4
.app
.FragmentManager
;
47 import android
.support
.v4
.app
.FragmentTransaction
;
48 import android
.view
.View
;
49 import android
.view
.ViewGroup
;
50 import android
.widget
.ArrayAdapter
;
51 import android
.widget
.TextView
;
52 import android
.widget
.Toast
;
54 import com
.actionbarsherlock
.app
.ActionBar
;
55 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
56 import com
.actionbarsherlock
.view
.Menu
;
57 import com
.actionbarsherlock
.view
.MenuInflater
;
58 import com
.actionbarsherlock
.view
.MenuItem
;
59 import com
.actionbarsherlock
.view
.Window
;
60 import com
.owncloud
.android
.BuildConfig
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
68 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
69 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
72 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
73 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
77 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
78 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
79 import com
.owncloud
.android
.operations
.CreateShareOperation
;
80 import com
.owncloud
.android
.operations
.MoveFileOperation
;
81 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
82 import com
.owncloud
.android
.operations
.RenameFileOperation
;
83 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
84 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
85 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
86 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
87 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
88 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
89 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
91 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
92 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
94 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
99 import com
.owncloud
.android
.utils
.DisplayUtils
;
100 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
103 import java
.io
.IOException
;
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
;
439 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
440 startTextPreview(mWaitingToPreview
);
441 detailsFragmentChanged
= true
;
443 getFileOperationsHelper().openFile(mWaitingToPreview
);
446 mWaitingToPreview
= null
;
448 if (!detailsFragmentChanged
) {
449 detailsFragment
.updateFileDetails(false
, (success
));
456 public boolean onPrepareOptionsMenu(Menu menu
) {
457 if (BuildConfig
.DEBUG
) {
458 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
460 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
462 return super.onPrepareOptionsMenu(menu
);
466 public boolean onCreateOptionsMenu(Menu menu
) {
467 MenuInflater inflater
= getSherlock().getMenuInflater();
468 inflater
.inflate(R
.menu
.main_menu
, menu
);
473 public boolean onOptionsItemSelected(MenuItem item
) {
474 boolean retval
= true
;
475 switch (item
.getItemId()) {
476 case R
.id
.action_create_dir
: {
477 CreateFolderDialogFragment dialog
=
478 CreateFolderDialogFragment
.newInstance(getCurrentDir());
479 dialog
.show(getSupportFragmentManager(), "createdirdialog");
482 case R
.id
.action_sync_account
: {
483 startSynchronization();
486 case R
.id
.action_upload
: {
487 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
490 case R
.id
.action_settings
: {
491 Intent settingsIntent
= new Intent(this, Preferences
.class);
492 startActivity(settingsIntent
);
495 case R
.id
.action_logger
: {
496 Intent loggerIntent
= new Intent(getApplicationContext(), LogHistoryActivity
.class);
497 startActivity(loggerIntent
);
500 case android
.R
.id
.home
: {
501 FileFragment second
= getSecondFragment();
502 OCFile currentDir
= getCurrentDir();
503 if ((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
504 (second
!= null
&& second
.getFile() != null
)) {
511 retval
= super.onOptionsItemSelected(item
);
516 private void startSynchronization() {
517 Log_OC
.e(TAG
, "Got to start sync");
518 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
519 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
520 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
521 Bundle bundle
= new Bundle();
522 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
523 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
524 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
525 ContentResolver
.requestSync(
527 MainApp
.getAuthority(), bundle
);
529 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
530 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
531 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
532 builder
.setExpedited(true
);
533 builder
.setManual(true
);
535 SyncRequest request
= builder
.build();
536 ContentResolver
.requestSync(request
);
542 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
543 if (itemPosition
!= 0) {
544 String targetPath
= "";
545 for (int i
= itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
546 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
548 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
549 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
550 if (targetFolder
!= null
) {
551 browseTo(targetFolder
);
554 // the next operation triggers a new call to this method, but it's necessary to
555 // ensure that the name exposed in the action bar is the current directory when the
556 // user selected it in the navigation list
557 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
558 getSupportActionBar().setSelectedNavigationItem(0);
564 * Called, when the user selected something for uploading
566 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
567 super.onActivityResult(requestCode
, resultCode
, data
);
569 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
570 requestSimpleUpload(data
, resultCode
);
572 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
573 requestMultipleUpload(data
, resultCode
);
575 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
576 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)) {
578 final Intent fData
= data
;
579 final int fResultCode
= resultCode
;
580 getHandler().postDelayed(
584 requestMoveOperation(fData
, fResultCode
);
587 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
592 private void requestMultipleUpload(Intent data
, int resultCode
) {
593 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
594 if (filePaths
!= null
) {
595 String
[] remotePaths
= new String
[filePaths
.length
];
596 String remotePathBase
= "";
597 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
598 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
600 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
601 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
602 for (int j
= 0; j
< remotePaths
.length
; j
++) {
603 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
606 Intent i
= new Intent(this, FileUploader
.class);
607 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
608 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
609 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
610 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
611 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
612 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
616 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
617 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
624 private void requestSimpleUpload(Intent data
, int resultCode
) {
625 String filepath
= null
;
627 Uri selectedImageUri
= data
.getData();
629 String filemanagerstring
= selectedImageUri
.getPath();
630 String selectedImagePath
= getPath(selectedImageUri
);
632 if (selectedImagePath
!= null
)
633 filepath
= selectedImagePath
;
635 filepath
= filemanagerstring
;
637 } catch (Exception e
) {
638 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
642 if (filepath
== null
) {
643 Log_OC
.e(TAG
, "Couldnt resolve path to file");
644 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
650 Intent i
= new Intent(this, FileUploader
.class);
651 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
653 String remotepath
= new String();
654 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
655 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
657 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
658 remotepath
+= OCFile
.PATH_SEPARATOR
;
659 remotepath
+= new File(filepath
).getName();
661 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
662 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
663 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
664 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
665 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
670 * Request the operation for moving the file/folder from one path to another
672 * @param data Intent received
673 * @param resultCode Result code received
675 private void requestMoveOperation(Intent data
, int resultCode
) {
676 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
677 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
678 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
682 public void onBackPressed() {
683 OCFileListFragment listOfFiles
= getListOfFilesFragment();
684 if (mDualPane
|| getSecondFragment() == null
) {
685 if (listOfFiles
!= null
) { // should never be null, indeed
686 if (mDirectories
.getCount() <= 1) {
690 int levelsUp
= listOfFiles
.onBrowseUp();
691 for (int i
= 0; i
< levelsUp
&& mDirectories
.getCount() > 1; i
++) {
696 if (listOfFiles
!= null
) { // should never be null, indeed
697 setFile(listOfFiles
.getCurrentFile());
699 cleanSecondFragment();
704 protected void onSaveInstanceState(Bundle outState
) {
705 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
706 Log_OC
.e(TAG
, "onSaveInstanceState() start");
707 super.onSaveInstanceState(outState
);
708 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
709 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
710 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
711 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
713 Log_OC
.d(TAG
, "onSaveInstanceState() end");
718 protected void onResume() {
720 Log_OC
.e(TAG
, "onResume() start");
722 // refresh list of files
723 refreshListOfFilesFragment();
725 // Listen for sync messages
726 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
727 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
728 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
729 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
730 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
731 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
732 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
733 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
735 // Listen for upload messages
736 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
737 mUploadFinishReceiver
= new UploadFinishReceiver();
738 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
740 // Listen for download messages
741 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
742 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
743 mDownloadFinishReceiver
= new DownloadFinishReceiver();
744 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
746 Log_OC
.d(TAG
, "onResume() end");
751 protected void onPause() {
752 Log_OC
.e(TAG
, "onPause() start");
753 if (mSyncBroadcastReceiver
!= null
) {
754 unregisterReceiver(mSyncBroadcastReceiver
);
755 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
756 mSyncBroadcastReceiver
= null
;
758 if (mUploadFinishReceiver
!= null
) {
759 unregisterReceiver(mUploadFinishReceiver
);
760 mUploadFinishReceiver
= null
;
762 if (mDownloadFinishReceiver
!= null
) {
763 unregisterReceiver(mDownloadFinishReceiver
);
764 mDownloadFinishReceiver
= null
;
768 Log_OC
.d(TAG
, "onPause() end");
774 protected Dialog
onCreateDialog(int id
) {
775 Dialog dialog
= null
;
776 AlertDialog
.Builder builder
;
778 case DIALOG_SHORT_WAIT
: {
779 ProgressDialog working_dialog
= new ProgressDialog(this);
780 working_dialog
.setMessage(getResources().getString(
781 R
.string
.wait_a_moment
));
782 working_dialog
.setIndeterminate(true
);
783 working_dialog
.setCancelable(false
);
784 dialog
= working_dialog
;
787 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
790 String
[] allTheItems
= {getString(R
.string
.actionbar_upload_files
),
791 getString(R
.string
.actionbar_upload_from_apps
)};
793 builder
= new AlertDialog
.Builder(this);
794 builder
.setTitle(R
.string
.actionbar_upload
);
795 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
796 public void onClick(DialogInterface dialog
, int item
) {
799 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
800 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
801 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
803 // TODO create and handle new fragment
804 // LocalFileListFragment
806 } else if (item
== 1) {
807 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
808 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
809 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
810 ACTION_SELECT_CONTENT_FROM_APPS
);
814 dialog
= builder
.create();
817 case DIALOG_CERT_NOT_SAVED
: {
818 builder
= new AlertDialog
.Builder(this);
819 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
820 builder
.setCancelable(false
);
821 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
823 public void onClick(DialogInterface dialog
, int which
) {
829 dialog
= builder
.create();
841 * Translates a content URI of an image to a physical path
844 * @param uri The URI to resolve
845 * @return The path to the image or null if it could not be found
847 public String
getPath(Uri uri
) {
848 String
[] projection
= {MediaStore
.Images
.Media
.DATA
};
849 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
850 if (cursor
!= null
) {
851 int column_index
= cursor
852 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
853 cursor
.moveToFirst();
854 return cursor
.getString(column_index
);
860 * Pushes a directory to the drop down list
862 * @param directory to push
863 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
865 public void pushDirname(OCFile directory
) {
866 if (!directory
.isFolder()) {
867 throw new IllegalArgumentException("Only directories may be pushed!");
869 mDirectories
.insert(directory
.getFileName(), 0);
874 * Pops a directory name from the drop down list
876 * @return True, unless the stack is empty
878 public boolean popDirname() {
879 mDirectories
.remove(mDirectories
.getItem(0));
880 return !mDirectories
.isEmpty();
883 // Custom array adapter to override text colors
884 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
886 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
890 public View
getView(int position
, View convertView
, ViewGroup parent
) {
891 View v
= super.getView(position
, convertView
, parent
);
893 ((TextView
) v
).setTextColor(getResources().getColorStateList(
894 android
.R
.color
.white
));
896 fixRoot((TextView
) v
);
900 public View
getDropDownView(int position
, View convertView
,
902 View v
= super.getDropDownView(position
, convertView
, parent
);
904 ((TextView
) v
).setTextColor(getResources().getColorStateList(
905 android
.R
.color
.white
));
907 fixRoot((TextView
) v
);
911 private void fixRoot(TextView v
) {
912 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
913 v
.setText(R
.string
.default_display_name_for_root_folder
);
919 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
922 * {@link BroadcastReceiver} to enable syncing feedback in UI
925 public void onReceive(Context context
, Intent intent
) {
927 String event
= intent
.getAction();
928 Log_OC
.d(TAG
, "Received broadcast " + event
);
929 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
930 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
931 RemoteOperationResult synchResult
= (RemoteOperationResult
) intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
932 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
936 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
937 mSyncInProgress
= true
;
940 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
941 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
943 if (currentDir
== null
) {
944 // current folder was removed from the server
945 Toast
.makeText(FileDisplayActivity
.this,
946 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
952 if (currentFile
== null
&& !getFile().isFolder()) {
953 // currently selected file was removed in the server, and now we know it
954 cleanSecondFragment();
955 currentFile
= currentDir
;
958 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
959 OCFileListFragment fileListFragment
= getListOfFilesFragment();
960 if (fileListFragment
!= null
) {
961 fileListFragment
.listDirectory(currentDir
);
964 setFile(currentFile
);
967 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
969 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
971 /// TODO refactor and make common
972 synchResult
!= null
&& !synchResult
.isSuccess() &&
973 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
974 synchResult
.isIdPRedirection() ||
975 (synchResult
.isException() && synchResult
.getException()
976 instanceof AuthenticatorException
))) {
978 OwnCloudClient client
= null
;
980 OwnCloudAccount ocAccount
=
981 new OwnCloudAccount(getAccount(), context
);
982 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
983 removeClientFor(ocAccount
));
984 // TODO get rid of these exceptions
985 } catch (AccountNotFoundException e
) {
987 } catch (AuthenticatorException e
) {
989 } catch (OperationCanceledException e
) {
991 } catch (IOException e
) {
995 if (client
!= null
) {
996 OwnCloudCredentials cred
= client
.getCredentials();
998 AccountManager am
= AccountManager
.get(context
);
999 if (cred
.authTokenExpires()) {
1000 am
.invalidateAuthToken(
1005 am
.clearPassword(getAccount());
1010 requestCredentialsUpdate();
1014 removeStickyBroadcast(intent
);
1015 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1016 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1018 setBackgroundText();
1022 if (synchResult
!= null
) {
1023 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1024 mLastSslUntrustedServerResult
= synchResult
;
1027 } catch (RuntimeException e
) {
1028 // avoid app crashes after changing the serial id of RemoteOperationResult
1029 // in owncloud library with broadcast notifications pending to process
1030 removeStickyBroadcast(intent
);
1036 * Show a text message on screen view for notifying user if content is
1037 * loading or folder is empty
1039 private void setBackgroundText() {
1040 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1041 if (ocFileListFragment
!= null
) {
1042 int message
= R
.string
.file_list_loading
;
1043 if (!mSyncInProgress
) {
1044 // In case file list is empty
1045 message
= R
.string
.file_list_empty
;
1047 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1049 Log_OC
.e(TAG
, "OCFileListFragment is null");
1054 * Once the file upload has finished -> update view
1056 private class UploadFinishReceiver
extends BroadcastReceiver
{
1058 * Once the file upload has finished -> update view
1060 * @author David A. Velasco
1061 * {@link BroadcastReceiver} to enable upload feedback in UI
1064 public void onReceive(Context context
, Intent intent
) {
1066 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1067 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1068 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1069 OCFile currentDir
= getCurrentDir();
1070 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1071 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1073 if (sameAccount
&& isDescendant
) {
1074 refreshListOfFilesFragment();
1077 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1078 boolean renamedInUpload
= getFile().getRemotePath().
1079 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1080 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1082 FileFragment details
= getSecondFragment();
1083 boolean detailFragmentIsShown
= (details
!= null
&&
1084 details
instanceof FileDetailFragment
);
1086 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1087 if (uploadWasFine
) {
1088 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1090 if (renamedInUpload
) {
1091 String newName
= (new File(uploadedRemotePath
)).getName();
1092 Toast msg
= Toast
.makeText(
1095 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1100 if (uploadWasFine
|| getFile().fileExists()) {
1101 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1103 cleanSecondFragment();
1106 // Force the preview if the file is an image or text file
1107 if (uploadWasFine
) {
1108 OCFile ocFile
= getFile();
1109 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1110 startImagePreview(getFile());
1111 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1112 startTextPreview(ocFile
);
1113 // TODO what about other kind of previews?
1118 if (intent
!= null
) {
1119 removeStickyBroadcast(intent
);
1129 * Class waiting for broadcast events from the {@link FileDownloader} service.
1131 * Updates the UI when a download is started or finished, provided that it is relevant for the
1134 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1136 public void onReceive(Context context
, Intent intent
) {
1138 boolean sameAccount
= isSameAccount(context
, intent
);
1139 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1140 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1142 if (sameAccount
&& isDescendant
) {
1143 refreshListOfFilesFragment();
1144 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1147 if (mWaitingToSend
!= null
) {
1148 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1149 if (mWaitingToSend
.isDown()) {
1150 sendDownloadedFile();
1155 if (intent
!= null
) {
1156 removeStickyBroadcast(intent
);
1161 private boolean isDescendant(String downloadedRemotePath
) {
1162 OCFile currentDir
= getCurrentDir();
1163 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1166 private boolean isSameAccount(Context context
, Intent intent
) {
1167 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1168 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1173 public void browseToRoot() {
1174 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1175 if (listOfFiles
!= null
) { // should never be null, indeed
1176 while (mDirectories
.getCount() > 1) {
1179 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1180 listOfFiles
.listDirectory(root
);
1181 setFile(listOfFiles
.getCurrentFile());
1182 startSyncFolderOperation(root
, false
);
1184 cleanSecondFragment();
1188 public void browseTo(OCFile folder
) {
1189 if (folder
== null
|| !folder
.isFolder()) {
1190 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1192 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1193 if (listOfFiles
!= null
) {
1194 setNavigationListWithFolder(folder
);
1195 listOfFiles
.listDirectory(folder
);
1196 setFile(listOfFiles
.getCurrentFile());
1197 startSyncFolderOperation(folder
, false
);
1199 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1201 cleanSecondFragment();
1208 * Updates action bar and second fragment, if in dual pane mode.
1211 public void onBrowsedDownTo(OCFile directory
) {
1212 pushDirname(directory
);
1213 cleanSecondFragment();
1216 startSyncFolderOperation(directory
, false
);
1221 * Shows the information of the {@link OCFile} received as a
1222 * parameter in the second fragment.
1224 * @param file {@link OCFile} whose details will be shown
1227 public void showDetails(OCFile file
) {
1228 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1229 setSecondFragment(detailFragment
);
1230 updateFragmentsVisibility(true
);
1231 updateNavigationElementsInActionBar(file
);
1239 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1240 ActionBar actionBar
= getSupportActionBar();
1241 if (chosenFile
== null
|| mDualPane
) {
1242 // only list of files - set for browsing through folders
1243 OCFile currentDir
= getCurrentDir();
1244 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1245 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1246 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1248 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1250 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1251 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1254 actionBar
.setDisplayHomeAsUpEnabled(true
);
1255 actionBar
.setDisplayShowTitleEnabled(true
);
1256 actionBar
.setTitle(chosenFile
.getFileName());
1257 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1263 protected ServiceConnection
newTransferenceServiceConnection() {
1264 return new ListServiceConnection();
1268 * 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
;
1320 * Launch an intent to request the PIN code to the user before letting him use the app
1322 private void requestPinCode() {
1323 boolean pinStart
= false
;
1324 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1325 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1327 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1328 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1335 public void onSavedCertificate() {
1336 startSyncFolderOperation(getCurrentDir(), false
);
1341 public void onFailedSavingCertificate() {
1342 showDialog(DIALOG_CERT_NOT_SAVED
);
1346 public void onCancelCertificate() {
1351 * Updates the view associated to the activity after the finish of some operation over files
1352 * in the current account.
1354 * @param operation Removal operation performed.
1355 * @param result Result of the removal.
1358 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1359 super.onRemoteOperationFinish(operation
, result
);
1361 if (operation
instanceof RemoveFileOperation
) {
1362 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1364 } else if (operation
instanceof RenameFileOperation
) {
1365 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1367 } else if (operation
instanceof SynchronizeFileOperation
) {
1368 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1370 } else if (operation
instanceof CreateFolderOperation
) {
1371 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1373 } else if (operation
instanceof CreateShareOperation
) {
1374 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1376 } else if (operation
instanceof UnshareLinkOperation
) {
1377 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1379 } else if (operation
instanceof MoveFileOperation
) {
1380 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1386 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1387 if (result
.isSuccess()) {
1388 refreshShowDetails();
1389 refreshListOfFilesFragment();
1394 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1395 if (result
.isSuccess()) {
1396 refreshShowDetails();
1397 refreshListOfFilesFragment();
1399 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1400 cleanSecondFragment();
1401 refreshListOfFilesFragment();
1405 private void refreshShowDetails() {
1406 FileFragment details
= getSecondFragment();
1407 if (details
!= null
) {
1408 OCFile file
= details
.getFile();
1410 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1411 if (details
instanceof PreviewMediaFragment
) {
1412 // Refresh OCFile of the fragment
1413 ((PreviewMediaFragment
) details
).updateFile(file
);
1418 invalidateOptionsMenu();
1423 * Updates the view associated to the activity after the finish of an operation trying to remove a
1426 * @param operation Removal operation performed.
1427 * @param result Result of the removal.
1429 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1430 dismissLoadingDialog();
1432 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1436 if (result
.isSuccess()) {
1437 OCFile removedFile
= operation
.getFile();
1438 FileFragment second
= getSecondFragment();
1439 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1440 if (second
instanceof PreviewMediaFragment
) {
1441 ((PreviewMediaFragment
) second
).stopPreview(true
);
1443 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1444 cleanSecondFragment();
1446 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1447 refreshListOfFilesFragment();
1449 invalidateOptionsMenu();
1451 if (result
.isSslRecoverableException()) {
1452 mLastSslUntrustedServerResult
= result
;
1453 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1460 * Updates the view associated to the activity after the finish of an operation trying to move a
1463 * @param operation Move operation performed.
1464 * @param result Result of the move operation.
1466 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1467 if (result
.isSuccess()) {
1468 dismissLoadingDialog();
1469 refreshListOfFilesFragment();
1471 dismissLoadingDialog();
1473 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1474 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1478 } catch (NotFoundException e
) {
1479 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1486 * Updates the view associated to the activity after the finish of an operation trying to rename a
1489 * @param operation Renaming operation performed.
1490 * @param result Result of the renaming.
1492 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1493 dismissLoadingDialog();
1494 OCFile renamedFile
= operation
.getFile();
1495 if (result
.isSuccess()) {
1496 FileFragment details
= getSecondFragment();
1497 if (details
!= null
) {
1498 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile())) {
1499 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1500 showDetails(renamedFile
);
1502 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1503 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1504 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1505 int position
= ((PreviewMediaFragment
) details
).getPosition();
1506 startMediaPreview(renamedFile
, position
, true
);
1508 getFileOperationsHelper().openFile(renamedFile
);
1510 } else if (details
instanceof PreviewTextFragment
&& renamedFile
.equals(details
.getFile())) {
1511 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1512 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1513 startTextPreview(renamedFile
);
1515 getFileOperationsHelper().openFile(renamedFile
);
1520 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1521 refreshListOfFilesFragment();
1525 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1529 if (result
.isSslRecoverableException()) {
1530 mLastSslUntrustedServerResult
= result
;
1531 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1536 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1537 dismissLoadingDialog();
1538 OCFile syncedFile
= operation
.getLocalFile();
1539 if (!result
.isSuccess()) {
1540 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1541 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1542 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1543 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1549 if (operation
.transferWasRequested()) {
1550 onTransferStateChanged(syncedFile
, true
, true
);
1553 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1561 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1563 * @param operation Creation operation performed.
1564 * @param result Result of the creation.
1566 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1567 if (result
.isSuccess()) {
1568 dismissLoadingDialog();
1569 refreshListOfFilesFragment();
1571 dismissLoadingDialog();
1573 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1574 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1578 } catch (NotFoundException e
) {
1579 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1589 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1590 refreshListOfFilesFragment();
1591 FileFragment details
= getSecondFragment();
1592 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile())) {
1593 if (downloading
|| uploading
) {
1594 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1596 if (!file
.fileExists()) {
1597 cleanSecondFragment();
1599 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1607 private void requestForDownload() {
1608 Account account
= getAccount();
1609 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1610 Intent i
= new Intent(this, FileDownloader
.class);
1611 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1612 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1618 private OCFile
getCurrentDir() {
1619 OCFile file
= getFile();
1621 if (file
.isFolder()) {
1623 } else if (getStorageManager() != null
) {
1624 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1625 return getStorageManager().getFileByPath(parentPath
);
1631 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1632 long currentSyncTime
= System
.currentTimeMillis();
1634 mSyncInProgress
= true
;
1636 // perform folder synchronization
1637 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation(folder
,
1640 getFileOperationsHelper().isSharedSupported(),
1642 getStorageManager(),
1644 getApplicationContext()
1646 synchFolderOp
.execute(getAccount(), this, null
, null
);
1648 setSupportProgressBarIndeterminateVisibility(true
);
1650 setBackgroundText();
1654 * Show untrusted cert dialog
1656 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1657 // Show a dialog with the certificate info
1658 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
) result
.getException());
1659 FragmentManager fm
= getSupportFragmentManager();
1660 FragmentTransaction ft
= fm
.beginTransaction();
1661 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1664 private void requestForDownload(OCFile file
) {
1665 Account account
= getAccount();
1666 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1667 Intent i
= new Intent(this, FileDownloader
.class);
1668 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1669 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1674 private void sendDownloadedFile() {
1675 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1676 mWaitingToSend
= null
;
1681 * Requests the download of the received {@link OCFile} , updates the UI
1682 * to monitor the download progress and prepares the activity to send the file
1683 * when the download finishes.
1685 * @param file {@link OCFile} to download and preview.
1687 public void startDownloadForSending(OCFile file
) {
1688 mWaitingToSend
= file
;
1689 requestForDownload(mWaitingToSend
);
1690 boolean hasSecondFragment
= (getSecondFragment() != null
);
1691 updateFragmentsVisibility(hasSecondFragment
);
1695 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1697 * @param file Image {@link OCFile} to show.
1699 public void startImagePreview(OCFile file
) {
1700 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1701 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1702 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1703 startActivity(showDetailsIntent
);
1707 * Stars the preview of an already down media {@link OCFile}.
1709 * @param file Media {@link OCFile} to preview.
1710 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1711 * @param autoplay When 'true', the playback will start without user interactions.
1713 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1714 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1715 setSecondFragment(mediaFragment
);
1716 updateFragmentsVisibility(true
);
1717 updateNavigationElementsInActionBar(file
);
1722 * Stars the preview of a text file {@link OCFile}.
1724 * @param file Text {@link OCFile} to preview.
1726 public void startTextPreview(OCFile file
) {
1727 Bundle args
= new Bundle();
1728 args
.putParcelable(EXTRA_FILE
, file
);
1729 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1730 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(), PreviewTextFragment
.class.getName(), args
);
1731 setSecondFragment(textPreviewFragment
);
1732 updateFragmentsVisibility(true
);
1733 updateNavigationElementsInActionBar(file
);
1738 * Requests the download of the received {@link OCFile} , updates the UI
1739 * to monitor the download progress and prepares the activity to preview
1740 * or open the file when the download finishes.
1742 * @param file {@link OCFile} to download and preview.
1744 public void startDownloadForPreview(OCFile file
) {
1745 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1746 setSecondFragment(detailFragment
);
1747 mWaitingToPreview
= file
;
1748 requestForDownload();
1749 updateFragmentsVisibility(true
);
1750 updateNavigationElementsInActionBar(file
);
1755 public void cancelTransference(OCFile file
) {
1756 getFileOperationsHelper().cancelTransference(file
);
1757 if (mWaitingToPreview
!= null
&&
1758 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1759 mWaitingToPreview
= null
;
1761 if (mWaitingToSend
!= null
&&
1762 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1763 mWaitingToSend
= null
;
1765 onTransferStateChanged(file
, false
, false
);
1769 public void onRefresh(boolean ignoreETag
) {
1770 refreshList(ignoreETag
);
1774 public void onRefresh() {
1778 private void refreshList(boolean ignoreETag
) {
1779 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1780 if (listOfFiles
!= null
) {
1781 OCFile folder
= listOfFiles
.getCurrentFile();
1782 if (folder
!= null
) {
1783 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1784 listDirectory(mFile);*/
1785 startSyncFolderOperation(folder
, ignoreETag
);