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
.Credentials
;
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.content.LocalBroadcastManager;
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
.FileObserverService
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
74 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
75 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
78 import com
.owncloud
.android
.lib
.common
.OwnCloudClientMap
;
79 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
;
80 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
81 import com
.owncloud
.android
.lib
.common
.network
.BearerCredentials
;
82 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
83 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
84 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
85 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
86 import com
.owncloud
.android
.operations
.CreateShareOperation
;
87 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
88 import com
.owncloud
.android
.operations
.RenameFileOperation
;
89 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
90 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
91 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
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
, OnSslUntrustedCertListener
{
118 private ArrayAdapter
<String
> mDirectories
;
120 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
121 private UploadFinishReceiver mUploadFinishReceiver
;
122 private DownloadFinishReceiver mDownloadFinishReceiver
;
123 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
125 private boolean mDualPane
;
126 private View mLeftFragmentContainer
;
127 private View mRightFragmentContainer
;
129 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
130 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
131 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
133 public static final int DIALOG_SHORT_WAIT
= 0;
134 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
135 private static final int DIALOG_CERT_NOT_SAVED
= 2;
137 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
139 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
140 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
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
) {
170 Intent observer_intent
= new Intent(this, FileObserverService
.class);
171 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
172 startService(observer_intent
);
174 /// Load of saved instance state
175 if(savedInstanceState
!= null
) {
176 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
177 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
178 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
181 mWaitingToPreview
= null
;
182 mSyncInProgress
= false
;
183 mWaitingToSend
= null
;
188 // Inflate and set the layout view
189 setContentView(R
.layout
.files
);
190 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
191 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
192 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
193 if (savedInstanceState
== null
) {
194 createMinFragments();
198 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
199 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
200 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
202 Log_OC
.d(TAG
, "onCreate() end");
206 protected void onStart() {
208 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
212 protected void onDestroy() {
217 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
220 protected void onAccountSet(boolean stateWasRecovered
) {
221 super.onAccountSet(stateWasRecovered
);
222 if (getAccount() != null
) {
223 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
224 OCFile file
= getFile();
225 // get parent from path
226 String parentPath
= "";
228 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
229 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
230 // get parent from path
231 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
232 if (getStorageManager().getFileByPath(parentPath
) == null
)
233 file
= null
; // not able to know the directory where the file is uploading
235 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
239 // fall back to root folder
240 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
243 setNavigationListWithFolder(file
);
245 if (!stateWasRecovered
) {
246 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
247 initFragmentsWithFile();
248 if (file
.isFolder()) {
249 startSyncFolderOperation(file
);
253 updateFragmentsVisibility(!file
.isFolder());
254 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
260 private void setNavigationListWithFolder(OCFile file
) {
261 mDirectories
.clear();
262 OCFile fileIt
= file
;
264 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
265 if (fileIt
.isFolder()) {
266 mDirectories
.add(fileIt
.getFileName());
268 // get parent from path
269 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
270 fileIt
= getStorageManager().getFileByPath(parentPath
);
272 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
276 private void createMinFragments() {
277 OCFileListFragment listOfFiles
= new OCFileListFragment();
278 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
279 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
280 transaction
.commit();
283 private void initFragmentsWithFile() {
284 if (getAccount() != null
&& getFile() != null
) {
286 OCFileListFragment listOfFiles
= getListOfFilesFragment();
287 if (listOfFiles
!= null
) {
288 listOfFiles
.listDirectory(getCurrentDir());
290 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
294 OCFile file
= getFile();
295 Fragment secondFragment
= chooseInitialSecondFragment(file
);
296 if (secondFragment
!= null
) {
297 setSecondFragment(secondFragment
);
298 updateFragmentsVisibility(true
);
299 updateNavigationElementsInActionBar(file
);
302 cleanSecondFragment();
306 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
307 if (getAccount() == null
) {
308 Log
.wtf(TAG
, "\t account is NULL");
310 if (getFile() == null
) {
311 Log
.wtf(TAG
, "\t file is NULL");
316 private Fragment
chooseInitialSecondFragment(OCFile file
) {
317 Fragment secondFragment
= null
;
318 if (file
!= null
&& !file
.isFolder()) {
319 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
320 && file
.getLastSyncDateForProperties() > 0 // temporal fix
322 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
323 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
324 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
327 secondFragment
= new FileDetailFragment(file
, getAccount());
330 return secondFragment
;
335 * Replaces the second fragment managed by the activity with the received as
338 * Assumes never will be more than two fragments managed at the same time.
340 * @param fragment New second Fragment to set.
342 private void setSecondFragment(Fragment fragment
) {
343 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
344 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
345 transaction
.commit();
349 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
351 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
352 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
354 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
355 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
358 } else if (existsSecondFragment
) {
359 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
360 mLeftFragmentContainer
.setVisibility(View
.GONE
);
362 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
363 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
367 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
370 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
371 mRightFragmentContainer
.setVisibility(View
.GONE
);
377 private OCFileListFragment
getListOfFilesFragment() {
378 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
379 if (listOfFiles
!= null
) {
380 return (OCFileListFragment
)listOfFiles
;
382 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
386 public FileFragment
getSecondFragment() {
387 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
388 if (second
!= null
) {
389 return (FileFragment
)second
;
394 protected void cleanSecondFragment() {
395 Fragment second
= getSecondFragment();
396 if (second
!= null
) {
397 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
401 updateFragmentsVisibility(false
);
402 updateNavigationElementsInActionBar(null
);
405 protected void refreshListOfFilesFragment() {
406 OCFileListFragment fileListFragment
= getListOfFilesFragment();
407 if (fileListFragment
!= null
) {
408 fileListFragment
.listDirectory();
412 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
413 FileFragment secondFragment
= getSecondFragment();
414 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
415 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
416 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
417 OCFile fileInFragment
= detailsFragment
.getFile();
418 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
419 // the user browsed to other file ; forget the automatic preview
420 mWaitingToPreview
= null
;
422 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
423 // grant that the right panel updates the progress bar
424 detailsFragment
.listenForTransferProgress();
425 detailsFragment
.updateFileDetails(true
, false
);
427 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
428 // update the right panel
429 boolean detailsFragmentChanged
= false
;
432 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
433 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
434 startMediaPreview(mWaitingToPreview
, 0, true
);
435 detailsFragmentChanged
= true
;
437 getFileOperationsHelper().openFile(mWaitingToPreview
);
440 mWaitingToPreview
= null
;
442 if (!detailsFragmentChanged
) {
443 detailsFragment
.updateFileDetails(false
, (success
));
450 public boolean onCreateOptionsMenu(Menu menu
) {
451 MenuInflater inflater
= getSherlock().getMenuInflater();
452 inflater
.inflate(R
.menu
.main_menu
, menu
);
457 public boolean onOptionsItemSelected(MenuItem item
) {
458 boolean retval
= true
;
459 switch (item
.getItemId()) {
460 case R
.id
.action_create_dir
: {
461 CreateFolderDialogFragment dialog
=
462 CreateFolderDialogFragment
.newInstance(getCurrentDir());
463 dialog
.show(getSupportFragmentManager(), "createdirdialog");
466 case R
.id
.action_sync_account
: {
467 startSynchronization();
470 case R
.id
.action_upload
: {
471 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
474 case R
.id
.action_settings
: {
475 Intent settingsIntent
= new Intent(this, Preferences
.class);
476 startActivity(settingsIntent
);
479 case android
.R
.id
.home
: {
480 FileFragment second
= getSecondFragment();
481 OCFile currentDir
= getCurrentDir();
482 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
483 (second
!= null
&& second
.getFile() != null
)) {
490 retval
= super.onOptionsItemSelected(item
);
495 private void startSynchronization() {
496 Log_OC
.e(TAG
, "Got to start sync");
497 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
498 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
499 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
500 Bundle bundle
= new Bundle();
501 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
502 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
503 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
504 ContentResolver
.requestSync(
506 MainApp
.getAuthority(), bundle
);
508 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
509 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
510 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
511 builder
.setExpedited(true
);
512 builder
.setManual(true
);
514 SyncRequest request
= builder
.build();
515 ContentResolver
.requestSync(request
);
521 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
522 if (itemPosition
!= 0) {
523 String targetPath
= "";
524 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
525 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
527 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
528 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
529 if (targetFolder
!= null
) {
530 browseTo(targetFolder
);
533 // the next operation triggers a new call to this method, but it's necessary to
534 // ensure that the name exposed in the action bar is the current directory when the
535 // user selected it in the navigation list
536 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
537 getSupportActionBar().setSelectedNavigationItem(0);
543 * Called, when the user selected something for uploading
545 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
546 super.onActivityResult(requestCode
, resultCode
, data
);
548 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
549 requestSimpleUpload(data
, resultCode
);
551 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
552 requestMultipleUpload(data
, resultCode
);
557 private void requestMultipleUpload(Intent data
, int resultCode
) {
558 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
559 if (filePaths
!= null
) {
560 String
[] remotePaths
= new String
[filePaths
.length
];
561 String remotePathBase
= "";
562 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
563 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
565 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
566 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
567 for (int j
= 0; j
< remotePaths
.length
; j
++) {
568 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
571 Intent i
= new Intent(this, FileUploader
.class);
572 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
573 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
574 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
575 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
576 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
577 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
581 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
582 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
589 private void requestSimpleUpload(Intent data
, int resultCode
) {
590 String filepath
= null
;
592 Uri selectedImageUri
= data
.getData();
594 String filemanagerstring
= selectedImageUri
.getPath();
595 String selectedImagePath
= getPath(selectedImageUri
);
597 if (selectedImagePath
!= null
)
598 filepath
= selectedImagePath
;
600 filepath
= filemanagerstring
;
602 } catch (Exception e
) {
603 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
607 if (filepath
== null
) {
608 Log_OC
.e(TAG
, "Couldnt resolve path to file");
609 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
615 Intent i
= new Intent(this, FileUploader
.class);
616 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
618 String remotepath
= new String();
619 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
620 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
622 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
623 remotepath
+= OCFile
.PATH_SEPARATOR
;
624 remotepath
+= new File(filepath
).getName();
626 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
627 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
628 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
629 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
630 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
635 public void onBackPressed() {
636 OCFileListFragment listOfFiles
= getListOfFilesFragment();
637 if (mDualPane
|| getSecondFragment() == null
) {
638 if (listOfFiles
!= null
) { // should never be null, indeed
639 if (mDirectories
.getCount() <= 1) {
643 int levelsUp
= listOfFiles
.onBrowseUp();
644 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
649 if (listOfFiles
!= null
) { // should never be null, indeed
650 setFile(listOfFiles
.getCurrentFile());
652 cleanSecondFragment();
657 protected void onSaveInstanceState(Bundle outState
) {
658 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
659 Log_OC
.e(TAG
, "onSaveInstanceState() start");
660 super.onSaveInstanceState(outState
);
661 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
662 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
663 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
664 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
666 Log_OC
.d(TAG
, "onSaveInstanceState() end");
672 protected void onResume() {
674 Log_OC
.e(TAG
, "onResume() start");
676 // refresh list of files
677 refreshListOfFilesFragment();
679 // Listen for sync messages
680 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
681 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
682 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
683 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
684 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
685 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
686 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
687 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
689 // Listen for upload messages
690 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
691 mUploadFinishReceiver
= new UploadFinishReceiver();
692 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
694 // Listen for download messages
695 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
696 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
697 mDownloadFinishReceiver
= new DownloadFinishReceiver();
698 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
700 Log_OC
.d(TAG
, "onResume() end");
705 protected void onPause() {
706 Log_OC
.e(TAG
, "onPause() start");
707 if (mSyncBroadcastReceiver
!= null
) {
708 unregisterReceiver(mSyncBroadcastReceiver
);
709 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
710 mSyncBroadcastReceiver
= null
;
712 if (mUploadFinishReceiver
!= null
) {
713 unregisterReceiver(mUploadFinishReceiver
);
714 mUploadFinishReceiver
= null
;
716 if (mDownloadFinishReceiver
!= null
) {
717 unregisterReceiver(mDownloadFinishReceiver
);
718 mDownloadFinishReceiver
= null
;
722 Log_OC
.d(TAG
, "onPause() end");
728 protected Dialog
onCreateDialog(int id
) {
729 Dialog dialog
= null
;
730 AlertDialog
.Builder builder
;
732 case DIALOG_SHORT_WAIT
: {
733 ProgressDialog working_dialog
= new ProgressDialog(this);
734 working_dialog
.setMessage(getResources().getString(
735 R
.string
.wait_a_moment
));
736 working_dialog
.setIndeterminate(true
);
737 working_dialog
.setCancelable(false
);
738 dialog
= working_dialog
;
741 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
743 String
[] items
= null
;
745 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
746 getString(R
.string
.actionbar_upload_from_apps
),
747 getString(R
.string
.actionbar_failed_instant_upload
) };
749 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
750 getString(R
.string
.actionbar_upload_from_apps
) };
752 if (InstantUploadActivity
.IS_ENABLED
)
757 builder
= new AlertDialog
.Builder(this);
758 builder
.setTitle(R
.string
.actionbar_upload
);
759 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
760 public void onClick(DialogInterface dialog
, int item
) {
763 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
764 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
765 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
767 // TODO create and handle new fragment
768 // LocalFileListFragment
770 } else if (item
== 1) {
771 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
772 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
773 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
774 ACTION_SELECT_CONTENT_FROM_APPS
);
775 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
776 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
777 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
778 startActivity(action
);
782 dialog
= builder
.create();
785 case DIALOG_CERT_NOT_SAVED
: {
786 builder
= new AlertDialog
.Builder(this);
787 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
788 builder
.setCancelable(false
);
789 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
791 public void onClick(DialogInterface dialog
, int which
) {
795 dialog
= builder
.create();
807 * Translates a content URI of an image to a physical path
809 * @param uri The URI to resolve
810 * @return The path to the image or null if it could not be found
812 public String
getPath(Uri uri
) {
813 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
814 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
815 if (cursor
!= null
) {
816 int column_index
= cursor
817 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
818 cursor
.moveToFirst();
819 return cursor
.getString(column_index
);
825 * Pushes a directory to the drop down list
826 * @param directory to push
827 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
829 public void pushDirname(OCFile directory
) {
830 if(!directory
.isFolder()){
831 throw new IllegalArgumentException("Only directories may be pushed!");
833 mDirectories
.insert(directory
.getFileName(), 0);
838 * Pops a directory name from the drop down list
839 * @return True, unless the stack is empty
841 public boolean popDirname() {
842 mDirectories
.remove(mDirectories
.getItem(0));
843 return !mDirectories
.isEmpty();
846 // Custom array adapter to override text colors
847 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
849 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
853 public View
getView(int position
, View convertView
, ViewGroup parent
) {
854 View v
= super.getView(position
, convertView
, parent
);
856 ((TextView
) v
).setTextColor(getResources().getColorStateList(
857 android
.R
.color
.white
));
859 fixRoot((TextView
) v
);
863 public View
getDropDownView(int position
, View convertView
,
865 View v
= super.getDropDownView(position
, convertView
, parent
);
867 ((TextView
) v
).setTextColor(getResources().getColorStateList(
868 android
.R
.color
.white
));
870 fixRoot((TextView
) v
);
874 private void fixRoot(TextView v
) {
875 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
876 v
.setText(R
.string
.default_display_name_for_root_folder
);
882 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
885 * {@link BroadcastReceiver} to enable syncing feedback in UI
888 public void onReceive(Context context
, Intent intent
) {
890 String event
= intent
.getAction();
891 Log_OC
.d(TAG
, "Received broadcast " + event
);
892 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
893 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
894 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
895 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
899 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
900 mSyncInProgress
= true
;
903 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
904 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
906 if (currentDir
== null
) {
907 // current folder was removed from the server
908 Toast
.makeText( FileDisplayActivity
.this,
909 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
915 if (currentFile
== null
&& !getFile().isFolder()) {
916 // currently selected file was removed in the server, and now we know it
917 cleanSecondFragment();
918 currentFile
= currentDir
;
921 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
922 OCFileListFragment fileListFragment
= getListOfFilesFragment();
923 if (fileListFragment
!= null
) {
924 fileListFragment
.listDirectory(currentDir
);
927 setFile(currentFile
);
930 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
932 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
934 /// TODO refactor and make common
935 synchResult
!= null
&& !synchResult
.isSuccess() &&
936 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
937 synchResult
.isIdPRedirection() ||
938 (synchResult
.isException() && synchResult
.getException()
939 instanceof AuthenticatorException
))) {
942 OwnCloudClient client
= OwnCloudClientMap
.removeClientFor(getAccount());
943 if (client
!= null
) {
944 Credentials cred
= client
.getCredentials();
945 String ssoSessionCookie
= client
.getSsoSessionCookie();
946 if (cred
!= null
|| ssoSessionCookie
!= null
) {
947 boolean bearerAuthorization
= (cred
!= null
&& cred
instanceof BearerCredentials
);
948 boolean samlBasedSsoAuthorization
= (cred
== null
&& ssoSessionCookie
!= null
);
949 AccountManager am
= AccountManager
.get(context
);
951 if (bearerAuthorization
) {
952 am
.invalidateAuthToken(getAccount().type
,
953 ((BearerCredentials
)cred
).getAccessToken());
955 } else if (samlBasedSsoAuthorization
) {
956 am
.invalidateAuthToken(getAccount().type
, ssoSessionCookie
);
959 am
.clearPassword(getAccount());
964 requestCredentialsUpdate();
968 removeStickyBroadcast(intent
);
969 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
970 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
974 if (synchResult
!= null
) {
975 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
976 mLastSslUntrustedServerResult
= synchResult
;
979 } catch (RuntimeException e
) {
980 // avoid app crashes after changing the serial id of RemoteOperationResult
981 // in owncloud library with broadcast notifications pending to process
982 removeStickyBroadcast(intent
);
989 * Once the file upload has finished -> update view
991 private class UploadFinishReceiver
extends BroadcastReceiver
{
993 * Once the file upload has finished -> update view
994 * @author David A. Velasco
995 * {@link BroadcastReceiver} to enable upload feedback in UI
998 public void onReceive(Context context
, Intent intent
) {
999 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1000 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1001 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1002 OCFile currentDir
= getCurrentDir();
1003 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1004 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1006 if (sameAccount
&& isDescendant
) {
1007 refreshListOfFilesFragment();
1010 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1011 boolean renamedInUpload
= getFile().getRemotePath().
1012 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1013 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1015 FileFragment details
= getSecondFragment();
1016 boolean detailFragmentIsShown
= (details
!= null
&&
1017 details
instanceof FileDetailFragment
);
1019 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1020 if (uploadWasFine
) {
1021 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1023 if (renamedInUpload
) {
1024 String newName
= (new File(uploadedRemotePath
)).getName();
1025 Toast msg
= Toast
.makeText(
1028 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1033 if (uploadWasFine
|| getFile().fileExists()) {
1034 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1036 cleanSecondFragment();
1039 // Force the preview if the file is an image
1040 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1041 startImagePreview(getFile());
1042 } // TODO what about other kind of previews?
1045 removeStickyBroadcast(intent
);
1053 * Class waiting for broadcast events from the {@link FielDownloader} service.
1055 * Updates the UI when a download is started or finished, provided that it is relevant for the
1058 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1060 public void onReceive(Context context
, Intent intent
) {
1061 boolean sameAccount
= isSameAccount(context
, intent
);
1062 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1063 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1065 if (sameAccount
&& isDescendant
) {
1066 refreshListOfFilesFragment();
1067 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1070 if (mWaitingToSend
!= null
) {
1071 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1072 if (mWaitingToSend
.isDown()) {
1073 sendDownloadedFile();
1077 removeStickyBroadcast(intent
);
1080 private boolean isDescendant(String downloadedRemotePath
) {
1081 OCFile currentDir
= getCurrentDir();
1082 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1085 private boolean isSameAccount(Context context
, Intent intent
) {
1086 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1087 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1092 public void browseToRoot() {
1093 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1094 if (listOfFiles
!= null
) { // should never be null, indeed
1095 while (mDirectories
.getCount() > 1) {
1098 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1099 listOfFiles
.listDirectory(root
);
1100 setFile(listOfFiles
.getCurrentFile());
1101 startSyncFolderOperation(root
);
1103 cleanSecondFragment();
1107 public void browseTo(OCFile folder
) {
1108 if (folder
== null
|| !folder
.isFolder()) {
1109 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1111 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1112 if (listOfFiles
!= null
) {
1113 setNavigationListWithFolder(folder
);
1114 listOfFiles
.listDirectory(folder
);
1115 setFile(listOfFiles
.getCurrentFile());
1116 startSyncFolderOperation(folder
);
1118 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1120 cleanSecondFragment();
1127 * Updates action bar and second fragment, if in dual pane mode.
1130 public void onBrowsedDownTo(OCFile directory
) {
1131 pushDirname(directory
);
1132 cleanSecondFragment();
1135 startSyncFolderOperation(directory
);
1140 * Shows the information of the {@link OCFile} received as a
1141 * parameter in the second fragment.
1143 * @param file {@link OCFile} whose details will be shown
1146 public void showDetails(OCFile file
) {
1147 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1148 setSecondFragment(detailFragment
);
1149 updateFragmentsVisibility(true
);
1150 updateNavigationElementsInActionBar(file
);
1158 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1159 ActionBar actionBar
= getSupportActionBar();
1160 if (chosenFile
== null
|| mDualPane
) {
1161 // only list of files - set for browsing through folders
1162 OCFile currentDir
= getCurrentDir();
1163 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1164 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1165 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1167 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1169 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1170 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1173 actionBar
.setDisplayHomeAsUpEnabled(true
);
1174 actionBar
.setDisplayShowTitleEnabled(true
);
1175 actionBar
.setTitle(chosenFile
.getFileName());
1176 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1182 protected ServiceConnection
newTransferenceServiceConnection() {
1183 return new ListServiceConnection();
1186 /** Defines callbacks for service binding, passed to bindService() */
1187 private class ListServiceConnection
implements ServiceConnection
{
1190 public void onServiceConnected(ComponentName component
, IBinder service
) {
1191 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1192 Log_OC
.d(TAG
, "Download service connected");
1193 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1194 if (mWaitingToPreview
!= null
)
1195 if (getStorageManager() != null
) {
1196 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1197 if (!mWaitingToPreview
.isDown()) {
1198 requestForDownload();
1202 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1203 Log_OC
.d(TAG
, "Upload service connected");
1204 mUploaderBinder
= (FileUploaderBinder
) service
;
1208 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1209 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1210 if (listOfFiles
!= null
) {
1211 listOfFiles
.listDirectory();
1213 FileFragment secondFragment
= getSecondFragment();
1214 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1215 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1216 detailFragment
.listenForTransferProgress();
1217 detailFragment
.updateFileDetails(false
, false
);
1222 public void onServiceDisconnected(ComponentName component
) {
1223 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1224 Log_OC
.d(TAG
, "Download service disconnected");
1225 mDownloaderBinder
= null
;
1226 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1227 Log_OC
.d(TAG
, "Upload service disconnected");
1228 mUploaderBinder
= null
;
1236 * Launch an intent to request the PIN code to the user before letting him use the app
1238 private void requestPinCode() {
1239 boolean pinStart
= false
;
1240 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1241 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1243 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1244 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1251 public void onSavedCertificate() {
1252 startSyncFolderOperation(getCurrentDir());
1257 public void onFailedSavingCertificate() {
1258 showDialog(DIALOG_CERT_NOT_SAVED
);
1262 public void onCancelCertificate() {
1267 * Updates the view associated to the activity after the finish of some operation over files
1268 * in the current account.
1270 * @param operation Removal operation performed.
1271 * @param result Result of the removal.
1274 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1275 super.onRemoteOperationFinish(operation
, result
);
1277 if (operation
instanceof RemoveFileOperation
) {
1278 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1280 } else if (operation
instanceof RenameFileOperation
) {
1281 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1283 } else if (operation
instanceof SynchronizeFileOperation
) {
1284 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1286 } else if (operation
instanceof CreateFolderOperation
) {
1287 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1289 } else if (operation
instanceof CreateShareOperation
) {
1290 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1292 } else if (operation
instanceof UnshareLinkOperation
) {
1293 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1300 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1301 if (result
.isSuccess()) {
1302 refreshShowDetails();
1303 refreshListOfFilesFragment();
1308 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1309 if (result
.isSuccess()) {
1310 refreshShowDetails();
1311 refreshListOfFilesFragment();
1313 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1314 cleanSecondFragment();
1315 refreshListOfFilesFragment();
1319 private void refreshShowDetails() {
1320 FileFragment details
= getSecondFragment();
1321 if (details
!= null
) {
1322 OCFile file
= details
.getFile();
1324 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1325 if (details
instanceof PreviewMediaFragment
) {
1326 // Refresh OCFile of the fragment
1327 ((PreviewMediaFragment
) details
).updateFile(file
);
1332 invalidateOptionsMenu();
1337 * Updates the view associated to the activity after the finish of an operation trying to remove a
1340 * @param operation Removal operation performed.
1341 * @param result Result of the removal.
1343 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1344 dismissLoadingDialog();
1346 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1350 if (result
.isSuccess()) {
1351 OCFile removedFile
= operation
.getFile();
1352 FileFragment second
= getSecondFragment();
1353 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1354 if (second
instanceof PreviewMediaFragment
) {
1355 ((PreviewMediaFragment
)second
).stopPreview(true
);
1357 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1358 cleanSecondFragment();
1360 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1361 refreshListOfFilesFragment();
1363 invalidateOptionsMenu();
1365 if (result
.isSslRecoverableException()) {
1366 mLastSslUntrustedServerResult
= result
;
1367 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1374 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1376 * @param operation Creation operation performed.
1377 * @param result Result of the creation.
1379 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1380 if (result
.isSuccess()) {
1381 dismissLoadingDialog();
1382 refreshListOfFilesFragment();
1384 dismissLoadingDialog();
1386 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1387 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1391 } catch (NotFoundException e
) {
1392 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1399 * Updates the view associated to the activity after the finish of an operation trying to rename a
1402 * @param operation Renaming operation performed.
1403 * @param result Result of the renaming.
1405 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1406 dismissLoadingDialog();
1407 OCFile renamedFile
= operation
.getFile();
1408 if (result
.isSuccess()) {
1409 FileFragment details
= getSecondFragment();
1410 if (details
!= null
) {
1411 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1412 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1413 showDetails(renamedFile
);
1415 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1416 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1417 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1418 int position
= ((PreviewMediaFragment
)details
).getPosition();
1419 startMediaPreview(renamedFile
, position
, true
);
1421 getFileOperationsHelper().openFile(renamedFile
);
1426 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1427 refreshListOfFilesFragment();
1431 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1435 if (result
.isSslRecoverableException()) {
1436 mLastSslUntrustedServerResult
= result
;
1437 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1442 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1443 dismissLoadingDialog();
1444 OCFile syncedFile
= operation
.getLocalFile();
1445 if (!result
.isSuccess()) {
1446 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1447 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1448 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1449 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1455 if (operation
.transferWasRequested()) {
1456 onTransferStateChanged(syncedFile
, true
, true
);
1459 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1471 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1472 refreshListOfFilesFragment();
1473 FileFragment details
= getSecondFragment();
1474 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1475 if (downloading
|| uploading
) {
1476 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1478 if (!file
.fileExists()) {
1479 cleanSecondFragment();
1481 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1489 private void requestForDownload() {
1490 Account account
= getAccount();
1491 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1492 Intent i
= new Intent(this, FileDownloader
.class);
1493 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1494 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1500 private OCFile
getCurrentDir() {
1501 OCFile file
= getFile();
1503 if (file
.isFolder()) {
1505 } else if (getStorageManager() != null
) {
1506 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1507 return getStorageManager().getFileByPath(parentPath
);
1513 public void startSyncFolderOperation(OCFile folder
) {
1514 long currentSyncTime
= System
.currentTimeMillis();
1516 mSyncInProgress
= true
;
1518 // perform folder synchronization
1519 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1522 getFileOperationsHelper().isSharedSupported(),
1523 getStorageManager(),
1525 getApplicationContext()
1527 synchFolderOp
.execute(getAccount(), this, null
, null
);
1529 setSupportProgressBarIndeterminateVisibility(true
);
1533 * Show untrusted cert dialog
1535 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1536 // Show a dialog with the certificate info
1537 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1538 FragmentManager fm
= getSupportFragmentManager();
1539 FragmentTransaction ft
= fm
.beginTransaction();
1540 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1543 private void requestForDownload(OCFile file
) {
1544 Account account
= getAccount();
1545 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1546 Intent i
= new Intent(this, FileDownloader
.class);
1547 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1548 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1553 private void sendDownloadedFile(){
1554 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1555 mWaitingToSend
= null
;
1560 * Requests the download of the received {@link OCFile} , updates the UI
1561 * to monitor the download progress and prepares the activity to send the file
1562 * when the download finishes.
1564 * @param file {@link OCFile} to download and preview.
1566 public void startDownloadForSending(OCFile file
) {
1567 mWaitingToSend
= file
;
1568 requestForDownload(mWaitingToSend
);
1569 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1570 updateFragmentsVisibility(hasSecondFragment
);
1574 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1576 * @param file Image {@link OCFile} to show.
1578 public void startImagePreview(OCFile file
) {
1579 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1580 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1581 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1582 startActivity(showDetailsIntent
);
1587 * Stars the preview of an already down media {@link OCFile}.
1589 * @param file Media {@link OCFile} to preview.
1590 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1591 * @param autoplay When 'true', the playback will start without user interactions.
1593 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1594 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1595 setSecondFragment(mediaFragment
);
1596 updateFragmentsVisibility(true
);
1597 updateNavigationElementsInActionBar(file
);
1602 * Requests the download of the received {@link OCFile} , updates the UI
1603 * to monitor the download progress and prepares the activity to preview
1604 * or open the file when the download finishes.
1606 * @param file {@link OCFile} to download and preview.
1608 public void startDownloadForPreview(OCFile file
) {
1609 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1610 setSecondFragment(detailFragment
);
1611 mWaitingToPreview
= file
;
1612 requestForDownload();
1613 updateFragmentsVisibility(true
);
1614 updateNavigationElementsInActionBar(file
);
1619 public void cancelTransference(OCFile file
) {
1620 getFileOperationsHelper().cancelTransference(file
);
1621 if (mWaitingToPreview
!= null
&&
1622 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1623 mWaitingToPreview
= null
;
1625 if (mWaitingToSend
!= null
&&
1626 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1627 mWaitingToSend
= null
;
1629 onTransferStateChanged(file
, false
, false
);