1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 //import android.support.v4.content.LocalBroadcastManager;
52 import android
.util
.Log
;
53 import android
.view
.View
;
54 import android
.view
.ViewGroup
;
55 import android
.widget
.ArrayAdapter
;
56 import android
.widget
.TextView
;
57 import android
.widget
.Toast
;
59 import com
.actionbarsherlock
.app
.ActionBar
;
60 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
61 import com
.actionbarsherlock
.view
.Menu
;
62 import com
.actionbarsherlock
.view
.MenuInflater
;
63 import com
.actionbarsherlock
.view
.MenuItem
;
64 import com
.actionbarsherlock
.view
.Window
;
65 import com
.owncloud
.android
.MainApp
;
66 import com
.owncloud
.android
.R
;
67 import com
.owncloud
.android
.datamodel
.OCFile
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
72 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
78 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
79 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.operations
.CreateShareOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
94 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
101 import com
.owncloud
.android
.utils
.DisplayUtils
;
102 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
103 import com
.owncloud
.android
.utils
.Log_OC
;
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
, OnSslUntrustedCertListener
{
116 private ArrayAdapter
<String
> mDirectories
;
118 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
119 private UploadFinishReceiver mUploadFinishReceiver
;
120 private DownloadFinishReceiver mDownloadFinishReceiver
;
121 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
123 private boolean mDualPane
;
124 private View mLeftFragmentContainer
;
125 private View mRightFragmentContainer
;
127 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
128 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
129 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
131 public static final int DIALOG_SHORT_WAIT
= 0;
132 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
133 private static final int DIALOG_CERT_NOT_SAVED
= 2;
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
140 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
142 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
143 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
145 private OCFile mWaitingToPreview
;
147 private boolean mSyncInProgress
= false
;
149 private String DIALOG_UNTRUSTED_CERT
;
151 private OCFile mWaitingToSend
;
154 protected void onCreate(Bundle savedInstanceState
) {
155 Log_OC
.d(TAG
, "onCreate() start");
156 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
158 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
160 // PIN CODE request ; best location is to decide, let's try this first
161 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
163 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
167 /// grant that FileObserverService is watching favourite files
168 if (savedInstanceState
== null
) {
169 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
170 startService(initObserversIntent
);
173 /// Load of saved instance state
174 if(savedInstanceState
!= null
) {
175 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
180 mWaitingToPreview
= null
;
181 mSyncInProgress
= false
;
182 mWaitingToSend
= null
;
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
189 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
190 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
191 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
192 if (savedInstanceState
== null
) {
193 createMinFragments();
197 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
198 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
199 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
201 Log_OC
.d(TAG
, "onCreate() end");
205 protected void onStart() {
207 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
211 protected void onDestroy() {
216 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
219 protected void onAccountSet(boolean stateWasRecovered
) {
220 super.onAccountSet(stateWasRecovered
);
221 if (getAccount() != null
) {
222 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
223 OCFile file
= getFile();
224 // get parent from path
225 String parentPath
= "";
227 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
228 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
229 // get parent from path
230 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
231 if (getStorageManager().getFileByPath(parentPath
) == null
)
232 file
= null
; // not able to know the directory where the file is uploading
234 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
238 // fall back to root folder
239 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
242 setNavigationListWithFolder(file
);
244 if (!stateWasRecovered
) {
245 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
246 initFragmentsWithFile();
247 if (file
.isFolder()) {
248 startSyncFolderOperation(file
);
252 updateFragmentsVisibility(!file
.isFolder());
253 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
259 private void setNavigationListWithFolder(OCFile file
) {
260 mDirectories
.clear();
261 OCFile fileIt
= file
;
263 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
264 if (fileIt
.isFolder()) {
265 mDirectories
.add(fileIt
.getFileName());
267 // get parent from path
268 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
269 fileIt
= getStorageManager().getFileByPath(parentPath
);
271 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
275 private void createMinFragments() {
276 OCFileListFragment listOfFiles
= new OCFileListFragment();
277 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
278 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
279 transaction
.commit();
282 private void initFragmentsWithFile() {
283 if (getAccount() != null
&& getFile() != null
) {
285 OCFileListFragment listOfFiles
= getListOfFilesFragment();
286 if (listOfFiles
!= null
) {
287 listOfFiles
.listDirectory(getCurrentDir());
289 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
293 OCFile file
= getFile();
294 Fragment secondFragment
= chooseInitialSecondFragment(file
);
295 if (secondFragment
!= null
) {
296 setSecondFragment(secondFragment
);
297 updateFragmentsVisibility(true
);
298 updateNavigationElementsInActionBar(file
);
301 cleanSecondFragment();
305 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
306 if (getAccount() == null
) {
307 Log
.wtf(TAG
, "\t account is NULL");
309 if (getFile() == null
) {
310 Log
.wtf(TAG
, "\t file is NULL");
315 private Fragment
chooseInitialSecondFragment(OCFile file
) {
316 Fragment secondFragment
= null
;
317 if (file
!= null
&& !file
.isFolder()) {
318 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
319 && file
.getLastSyncDateForProperties() > 0 // temporal fix
321 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
322 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
323 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
326 secondFragment
= new FileDetailFragment(file
, getAccount());
329 return secondFragment
;
334 * Replaces the second fragment managed by the activity with the received as
337 * Assumes never will be more than two fragments managed at the same time.
339 * @param fragment New second Fragment to set.
341 private void setSecondFragment(Fragment fragment
) {
342 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
343 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
344 transaction
.commit();
348 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
350 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
351 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
353 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
354 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
357 } else if (existsSecondFragment
) {
358 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
359 mLeftFragmentContainer
.setVisibility(View
.GONE
);
361 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
362 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
366 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
369 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
370 mRightFragmentContainer
.setVisibility(View
.GONE
);
376 private OCFileListFragment
getListOfFilesFragment() {
377 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
378 if (listOfFiles
!= null
) {
379 return (OCFileListFragment
)listOfFiles
;
381 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
385 public FileFragment
getSecondFragment() {
386 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
387 if (second
!= null
) {
388 return (FileFragment
)second
;
393 protected void cleanSecondFragment() {
394 Fragment second
= getSecondFragment();
395 if (second
!= null
) {
396 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
400 updateFragmentsVisibility(false
);
401 updateNavigationElementsInActionBar(null
);
404 protected void refreshListOfFilesFragment() {
405 OCFileListFragment fileListFragment
= getListOfFilesFragment();
406 if (fileListFragment
!= null
) {
407 fileListFragment
.listDirectory();
411 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
412 FileFragment secondFragment
= getSecondFragment();
413 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
414 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
415 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
416 OCFile fileInFragment
= detailsFragment
.getFile();
417 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
418 // the user browsed to other file ; forget the automatic preview
419 mWaitingToPreview
= null
;
421 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
422 // grant that the right panel updates the progress bar
423 detailsFragment
.listenForTransferProgress();
424 detailsFragment
.updateFileDetails(true
, false
);
426 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
427 // update the right panel
428 boolean detailsFragmentChanged
= false
;
431 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
432 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
433 startMediaPreview(mWaitingToPreview
, 0, true
);
434 detailsFragmentChanged
= true
;
436 getFileOperationsHelper().openFile(mWaitingToPreview
);
439 mWaitingToPreview
= null
;
441 if (!detailsFragmentChanged
) {
442 detailsFragment
.updateFileDetails(false
, (success
));
449 public boolean onCreateOptionsMenu(Menu menu
) {
450 MenuInflater inflater
= getSherlock().getMenuInflater();
451 inflater
.inflate(R
.menu
.main_menu
, menu
);
456 public boolean onOptionsItemSelected(MenuItem item
) {
457 boolean retval
= true
;
458 switch (item
.getItemId()) {
459 case R
.id
.action_create_dir
: {
460 CreateFolderDialogFragment dialog
=
461 CreateFolderDialogFragment
.newInstance(getCurrentDir());
462 dialog
.show(getSupportFragmentManager(), "createdirdialog");
465 case R
.id
.action_sync_account
: {
466 startSynchronization();
469 case R
.id
.action_upload
: {
470 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
473 case R
.id
.action_settings
: {
474 Intent settingsIntent
= new Intent(this, Preferences
.class);
475 startActivity(settingsIntent
);
478 case android
.R
.id
.home
: {
479 FileFragment second
= getSecondFragment();
480 OCFile currentDir
= getCurrentDir();
481 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
482 (second
!= null
&& second
.getFile() != null
)) {
489 retval
= super.onOptionsItemSelected(item
);
494 private void startSynchronization() {
495 Log_OC
.e(TAG
, "Got to start sync");
496 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
497 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
498 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
499 Bundle bundle
= new Bundle();
500 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
501 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
502 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
503 ContentResolver
.requestSync(
505 MainApp
.getAuthority(), bundle
);
507 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
508 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
509 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
510 builder
.setExpedited(true
);
511 builder
.setManual(true
);
513 SyncRequest request
= builder
.build();
514 ContentResolver
.requestSync(request
);
520 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
521 if (itemPosition
!= 0) {
522 String targetPath
= "";
523 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
524 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
526 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
527 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
528 if (targetFolder
!= null
) {
529 browseTo(targetFolder
);
532 // the next operation triggers a new call to this method, but it's necessary to
533 // ensure that the name exposed in the action bar is the current directory when the
534 // user selected it in the navigation list
535 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
536 getSupportActionBar().setSelectedNavigationItem(0);
542 * Called, when the user selected something for uploading
544 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
545 super.onActivityResult(requestCode
, resultCode
, data
);
547 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
548 requestSimpleUpload(data
, resultCode
);
550 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
551 requestMultipleUpload(data
, resultCode
);
556 private void requestMultipleUpload(Intent data
, int resultCode
) {
557 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
558 if (filePaths
!= null
) {
559 String
[] remotePaths
= new String
[filePaths
.length
];
560 String remotePathBase
= "";
561 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
562 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
564 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
565 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
566 for (int j
= 0; j
< remotePaths
.length
; j
++) {
567 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
570 Intent i
= new Intent(this, FileUploader
.class);
571 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
572 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
573 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
574 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
575 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
576 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
580 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
581 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
588 private void requestSimpleUpload(Intent data
, int resultCode
) {
589 String filepath
= null
;
591 Uri selectedImageUri
= data
.getData();
593 String filemanagerstring
= selectedImageUri
.getPath();
594 String selectedImagePath
= getPath(selectedImageUri
);
596 if (selectedImagePath
!= null
)
597 filepath
= selectedImagePath
;
599 filepath
= filemanagerstring
;
601 } catch (Exception e
) {
602 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
606 if (filepath
== null
) {
607 Log_OC
.e(TAG
, "Couldnt resolve path to file");
608 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
614 Intent i
= new Intent(this, FileUploader
.class);
615 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
617 String remotepath
= new String();
618 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
619 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
621 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
622 remotepath
+= OCFile
.PATH_SEPARATOR
;
623 remotepath
+= new File(filepath
).getName();
625 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
626 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
627 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
628 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
629 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
634 public void onBackPressed() {
635 OCFileListFragment listOfFiles
= getListOfFilesFragment();
636 if (mDualPane
|| getSecondFragment() == null
) {
637 if (listOfFiles
!= null
) { // should never be null, indeed
638 if (mDirectories
.getCount() <= 1) {
642 int levelsUp
= listOfFiles
.onBrowseUp();
643 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
648 if (listOfFiles
!= null
) { // should never be null, indeed
649 setFile(listOfFiles
.getCurrentFile());
651 cleanSecondFragment();
656 protected void onSaveInstanceState(Bundle outState
) {
657 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
658 Log_OC
.e(TAG
, "onSaveInstanceState() start");
659 super.onSaveInstanceState(outState
);
660 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
661 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
662 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
663 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
665 Log_OC
.d(TAG
, "onSaveInstanceState() end");
671 protected void onResume() {
673 Log_OC
.e(TAG
, "onResume() start");
675 // refresh list of files
676 refreshListOfFilesFragment();
678 // Listen for sync messages
679 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
680 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
681 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
682 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
683 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
684 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
685 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
686 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
688 // Listen for upload messages
689 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
690 mUploadFinishReceiver
= new UploadFinishReceiver();
691 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
693 // Listen for download messages
694 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
695 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
696 mDownloadFinishReceiver
= new DownloadFinishReceiver();
697 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
699 Log_OC
.d(TAG
, "onResume() end");
704 protected void onPause() {
705 Log_OC
.e(TAG
, "onPause() start");
706 if (mSyncBroadcastReceiver
!= null
) {
707 unregisterReceiver(mSyncBroadcastReceiver
);
708 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
709 mSyncBroadcastReceiver
= null
;
711 if (mUploadFinishReceiver
!= null
) {
712 unregisterReceiver(mUploadFinishReceiver
);
713 mUploadFinishReceiver
= null
;
715 if (mDownloadFinishReceiver
!= null
) {
716 unregisterReceiver(mDownloadFinishReceiver
);
717 mDownloadFinishReceiver
= null
;
721 Log_OC
.d(TAG
, "onPause() end");
727 protected Dialog
onCreateDialog(int id
) {
728 Dialog dialog
= null
;
729 AlertDialog
.Builder builder
;
731 case DIALOG_SHORT_WAIT
: {
732 ProgressDialog working_dialog
= new ProgressDialog(this);
733 working_dialog
.setMessage(getResources().getString(
734 R
.string
.wait_a_moment
));
735 working_dialog
.setIndeterminate(true
);
736 working_dialog
.setCancelable(false
);
737 dialog
= working_dialog
;
740 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
742 String
[] items
= null
;
744 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
745 getString(R
.string
.actionbar_upload_from_apps
),
746 getString(R
.string
.actionbar_failed_instant_upload
) };
748 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
749 getString(R
.string
.actionbar_upload_from_apps
) };
751 if (InstantUploadActivity
.IS_ENABLED
)
756 builder
= new AlertDialog
.Builder(this);
757 builder
.setTitle(R
.string
.actionbar_upload
);
758 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
759 public void onClick(DialogInterface dialog
, int item
) {
762 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
763 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
764 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
766 // TODO create and handle new fragment
767 // LocalFileListFragment
769 } else if (item
== 1) {
770 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
771 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
772 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
773 ACTION_SELECT_CONTENT_FROM_APPS
);
774 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
775 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
776 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
777 startActivity(action
);
781 dialog
= builder
.create();
784 case DIALOG_CERT_NOT_SAVED
: {
785 builder
= new AlertDialog
.Builder(this);
786 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
787 builder
.setCancelable(false
);
788 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
790 public void onClick(DialogInterface dialog
, int which
) {
794 dialog
= builder
.create();
806 * Translates a content URI of an image to a physical path
808 * @param uri The URI to resolve
809 * @return The path to the image or null if it could not be found
811 public String
getPath(Uri uri
) {
812 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
813 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
814 if (cursor
!= null
) {
815 int column_index
= cursor
816 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
817 cursor
.moveToFirst();
818 return cursor
.getString(column_index
);
824 * Pushes a directory to the drop down list
825 * @param directory to push
826 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
828 public void pushDirname(OCFile directory
) {
829 if(!directory
.isFolder()){
830 throw new IllegalArgumentException("Only directories may be pushed!");
832 mDirectories
.insert(directory
.getFileName(), 0);
837 * Pops a directory name from the drop down list
838 * @return True, unless the stack is empty
840 public boolean popDirname() {
841 mDirectories
.remove(mDirectories
.getItem(0));
842 return !mDirectories
.isEmpty();
845 // Custom array adapter to override text colors
846 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
848 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
852 public View
getView(int position
, View convertView
, ViewGroup parent
) {
853 View v
= super.getView(position
, convertView
, parent
);
855 ((TextView
) v
).setTextColor(getResources().getColorStateList(
856 android
.R
.color
.white
));
858 fixRoot((TextView
) v
);
862 public View
getDropDownView(int position
, View convertView
,
864 View v
= super.getDropDownView(position
, convertView
, parent
);
866 ((TextView
) v
).setTextColor(getResources().getColorStateList(
867 android
.R
.color
.white
));
869 fixRoot((TextView
) v
);
873 private void fixRoot(TextView v
) {
874 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
875 v
.setText(R
.string
.default_display_name_for_root_folder
);
881 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
884 * {@link BroadcastReceiver} to enable syncing feedback in UI
887 public void onReceive(Context context
, Intent intent
) {
889 String event
= intent
.getAction();
890 Log_OC
.d(TAG
, "Received broadcast " + event
);
891 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
892 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
893 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
894 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
898 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
899 mSyncInProgress
= true
;
902 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
903 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
905 if (currentDir
== null
) {
906 // current folder was removed from the server
907 Toast
.makeText( FileDisplayActivity
.this,
908 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
914 if (currentFile
== null
&& !getFile().isFolder()) {
915 // currently selected file was removed in the server, and now we know it
916 cleanSecondFragment();
917 currentFile
= currentDir
;
920 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
921 OCFileListFragment fileListFragment
= getListOfFilesFragment();
922 if (fileListFragment
!= null
) {
923 fileListFragment
.listDirectory(currentDir
);
926 setFile(currentFile
);
929 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
931 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
933 /// TODO refactor and make common
934 synchResult
!= null
&& !synchResult
.isSuccess() &&
935 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
936 synchResult
.isIdPRedirection() ||
937 (synchResult
.isException() && synchResult
.getException()
938 instanceof AuthenticatorException
))) {
940 OwnCloudClient client
= null
;
942 OwnCloudAccount ocAccount
=
943 new OwnCloudAccount(getAccount(), context
);
944 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
945 removeClientFor(ocAccount
));
946 // TODO get rid of these exceptions
947 } catch (AccountNotFoundException e
) {
949 } catch (AuthenticatorException e
) {
951 } catch (OperationCanceledException e
) {
953 } catch (IOException e
) {
957 if (client
!= null
) {
958 OwnCloudCredentials cred
= client
.getCredentials();
960 AccountManager am
= AccountManager
.get(context
);
961 if (cred
.authTokenExpires()) {
962 am
.invalidateAuthToken(
967 am
.clearPassword(getAccount());
972 requestCredentialsUpdate();
976 removeStickyBroadcast(intent
);
977 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
978 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
982 if (synchResult
!= null
) {
983 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
984 mLastSslUntrustedServerResult
= synchResult
;
987 } catch (RuntimeException e
) {
988 // avoid app crashes after changing the serial id of RemoteOperationResult
989 // in owncloud library with broadcast notifications pending to process
990 removeStickyBroadcast(intent
);
997 * Once the file upload has finished -> update view
999 private class UploadFinishReceiver
extends BroadcastReceiver
{
1001 * Once the file upload has finished -> update view
1002 * @author David A. Velasco
1003 * {@link BroadcastReceiver} to enable upload feedback in UI
1006 public void onReceive(Context context
, Intent intent
) {
1008 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1009 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1010 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1011 OCFile currentDir
= getCurrentDir();
1012 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1013 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1015 if (sameAccount
&& isDescendant
) {
1016 refreshListOfFilesFragment();
1019 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1020 boolean renamedInUpload
= getFile().getRemotePath().
1021 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1022 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1024 FileFragment details
= getSecondFragment();
1025 boolean detailFragmentIsShown
= (details
!= null
&&
1026 details
instanceof FileDetailFragment
);
1028 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1029 if (uploadWasFine
) {
1030 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1032 if (renamedInUpload
) {
1033 String newName
= (new File(uploadedRemotePath
)).getName();
1034 Toast msg
= Toast
.makeText(
1037 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1042 if (uploadWasFine
|| getFile().fileExists()) {
1043 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1045 cleanSecondFragment();
1048 // Force the preview if the file is an image
1049 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1050 startImagePreview(getFile());
1051 } // TODO what about other kind of previews?
1055 if (intent
!= null
) {
1056 removeStickyBroadcast(intent
);
1066 * Class waiting for broadcast events from the {@link FielDownloader} service.
1068 * Updates the UI when a download is started or finished, provided that it is relevant for the
1071 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1073 public void onReceive(Context context
, Intent intent
) {
1075 boolean sameAccount
= isSameAccount(context
, intent
);
1076 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1077 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1079 if (sameAccount
&& isDescendant
) {
1080 refreshListOfFilesFragment();
1081 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1084 if (mWaitingToSend
!= null
) {
1085 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1086 if (mWaitingToSend
.isDown()) {
1087 sendDownloadedFile();
1092 if (intent
!= null
) {
1093 removeStickyBroadcast(intent
);
1098 private boolean isDescendant(String downloadedRemotePath
) {
1099 OCFile currentDir
= getCurrentDir();
1100 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1103 private boolean isSameAccount(Context context
, Intent intent
) {
1104 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1105 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1110 public void browseToRoot() {
1111 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1112 if (listOfFiles
!= null
) { // should never be null, indeed
1113 while (mDirectories
.getCount() > 1) {
1116 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1117 listOfFiles
.listDirectory(root
);
1118 setFile(listOfFiles
.getCurrentFile());
1119 startSyncFolderOperation(root
);
1121 cleanSecondFragment();
1125 public void browseTo(OCFile folder
) {
1126 if (folder
== null
|| !folder
.isFolder()) {
1127 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1129 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1130 if (listOfFiles
!= null
) {
1131 setNavigationListWithFolder(folder
);
1132 listOfFiles
.listDirectory(folder
);
1133 setFile(listOfFiles
.getCurrentFile());
1134 startSyncFolderOperation(folder
);
1136 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1138 cleanSecondFragment();
1145 * Updates action bar and second fragment, if in dual pane mode.
1148 public void onBrowsedDownTo(OCFile directory
) {
1149 pushDirname(directory
);
1150 cleanSecondFragment();
1153 startSyncFolderOperation(directory
);
1158 * Shows the information of the {@link OCFile} received as a
1159 * parameter in the second fragment.
1161 * @param file {@link OCFile} whose details will be shown
1164 public void showDetails(OCFile file
) {
1165 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1166 setSecondFragment(detailFragment
);
1167 updateFragmentsVisibility(true
);
1168 updateNavigationElementsInActionBar(file
);
1176 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1177 ActionBar actionBar
= getSupportActionBar();
1178 if (chosenFile
== null
|| mDualPane
) {
1179 // only list of files - set for browsing through folders
1180 OCFile currentDir
= getCurrentDir();
1181 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1182 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1183 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1185 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1187 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1188 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1191 actionBar
.setDisplayHomeAsUpEnabled(true
);
1192 actionBar
.setDisplayShowTitleEnabled(true
);
1193 actionBar
.setTitle(chosenFile
.getFileName());
1194 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1200 protected ServiceConnection
newTransferenceServiceConnection() {
1201 return new ListServiceConnection();
1204 /** Defines callbacks for service binding, passed to bindService() */
1205 private class ListServiceConnection
implements ServiceConnection
{
1208 public void onServiceConnected(ComponentName component
, IBinder service
) {
1209 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1210 Log_OC
.d(TAG
, "Download service connected");
1211 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1212 if (mWaitingToPreview
!= null
)
1213 if (getStorageManager() != null
) {
1214 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1215 if (!mWaitingToPreview
.isDown()) {
1216 requestForDownload();
1220 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1221 Log_OC
.d(TAG
, "Upload service connected");
1222 mUploaderBinder
= (FileUploaderBinder
) service
;
1226 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1227 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1228 if (listOfFiles
!= null
) {
1229 listOfFiles
.listDirectory();
1231 FileFragment secondFragment
= getSecondFragment();
1232 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1233 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1234 detailFragment
.listenForTransferProgress();
1235 detailFragment
.updateFileDetails(false
, false
);
1240 public void onServiceDisconnected(ComponentName component
) {
1241 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1242 Log_OC
.d(TAG
, "Download service disconnected");
1243 mDownloaderBinder
= null
;
1244 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1245 Log_OC
.d(TAG
, "Upload service disconnected");
1246 mUploaderBinder
= null
;
1254 * Launch an intent to request the PIN code to the user before letting him use the app
1256 private void requestPinCode() {
1257 boolean pinStart
= false
;
1258 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1259 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1261 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1262 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1269 public void onSavedCertificate() {
1270 startSyncFolderOperation(getCurrentDir());
1275 public void onFailedSavingCertificate() {
1276 showDialog(DIALOG_CERT_NOT_SAVED
);
1280 public void onCancelCertificate() {
1285 * Updates the view associated to the activity after the finish of some operation over files
1286 * in the current account.
1288 * @param operation Removal operation performed.
1289 * @param result Result of the removal.
1292 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1293 super.onRemoteOperationFinish(operation
, result
);
1295 if (operation
instanceof RemoveFileOperation
) {
1296 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1298 } else if (operation
instanceof RenameFileOperation
) {
1299 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1301 } else if (operation
instanceof SynchronizeFileOperation
) {
1302 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1304 } else if (operation
instanceof CreateFolderOperation
) {
1305 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1307 } else if (operation
instanceof CreateShareOperation
) {
1308 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1310 } else if (operation
instanceof UnshareLinkOperation
) {
1311 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1318 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1319 if (result
.isSuccess()) {
1320 refreshShowDetails();
1321 refreshListOfFilesFragment();
1326 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1327 if (result
.isSuccess()) {
1328 refreshShowDetails();
1329 refreshListOfFilesFragment();
1331 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1332 cleanSecondFragment();
1333 refreshListOfFilesFragment();
1337 private void refreshShowDetails() {
1338 FileFragment details
= getSecondFragment();
1339 if (details
!= null
) {
1340 OCFile file
= details
.getFile();
1342 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1343 if (details
instanceof PreviewMediaFragment
) {
1344 // Refresh OCFile of the fragment
1345 ((PreviewMediaFragment
) details
).updateFile(file
);
1350 invalidateOptionsMenu();
1355 * Updates the view associated to the activity after the finish of an operation trying to remove a
1358 * @param operation Removal operation performed.
1359 * @param result Result of the removal.
1361 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1362 dismissLoadingDialog();
1364 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1368 if (result
.isSuccess()) {
1369 OCFile removedFile
= operation
.getFile();
1370 FileFragment second
= getSecondFragment();
1371 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1372 if (second
instanceof PreviewMediaFragment
) {
1373 ((PreviewMediaFragment
)second
).stopPreview(true
);
1375 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1376 cleanSecondFragment();
1378 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1379 refreshListOfFilesFragment();
1381 invalidateOptionsMenu();
1383 if (result
.isSslRecoverableException()) {
1384 mLastSslUntrustedServerResult
= result
;
1385 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1392 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1394 * @param operation Creation operation performed.
1395 * @param result Result of the creation.
1397 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1398 if (result
.isSuccess()) {
1399 dismissLoadingDialog();
1400 refreshListOfFilesFragment();
1402 dismissLoadingDialog();
1404 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1405 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1409 } catch (NotFoundException e
) {
1410 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1417 * Updates the view associated to the activity after the finish of an operation trying to rename a
1420 * @param operation Renaming operation performed.
1421 * @param result Result of the renaming.
1423 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1424 dismissLoadingDialog();
1425 OCFile renamedFile
= operation
.getFile();
1426 if (result
.isSuccess()) {
1427 FileFragment details
= getSecondFragment();
1428 if (details
!= null
) {
1429 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1430 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1431 showDetails(renamedFile
);
1433 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1434 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1435 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1436 int position
= ((PreviewMediaFragment
)details
).getPosition();
1437 startMediaPreview(renamedFile
, position
, true
);
1439 getFileOperationsHelper().openFile(renamedFile
);
1444 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1445 refreshListOfFilesFragment();
1449 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1453 if (result
.isSslRecoverableException()) {
1454 mLastSslUntrustedServerResult
= result
;
1455 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1460 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1461 dismissLoadingDialog();
1462 OCFile syncedFile
= operation
.getLocalFile();
1463 if (!result
.isSuccess()) {
1464 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1465 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1466 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1467 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1473 if (operation
.transferWasRequested()) {
1474 onTransferStateChanged(syncedFile
, true
, true
);
1477 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1489 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1490 refreshListOfFilesFragment();
1491 FileFragment details
= getSecondFragment();
1492 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1493 if (downloading
|| uploading
) {
1494 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1496 if (!file
.fileExists()) {
1497 cleanSecondFragment();
1499 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1507 private void requestForDownload() {
1508 Account account
= getAccount();
1509 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1510 Intent i
= new Intent(this, FileDownloader
.class);
1511 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1512 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1518 private OCFile
getCurrentDir() {
1519 OCFile file
= getFile();
1521 if (file
.isFolder()) {
1523 } else if (getStorageManager() != null
) {
1524 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1525 return getStorageManager().getFileByPath(parentPath
);
1531 public void startSyncFolderOperation(OCFile folder
) {
1532 long currentSyncTime
= System
.currentTimeMillis();
1534 mSyncInProgress
= true
;
1536 // perform folder synchronization
1537 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1540 getFileOperationsHelper().isSharedSupported(),
1541 getStorageManager(),
1543 getApplicationContext()
1545 synchFolderOp
.execute(getAccount(), this, null
, null
);
1547 setSupportProgressBarIndeterminateVisibility(true
);
1551 * Show untrusted cert dialog
1553 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1554 // Show a dialog with the certificate info
1555 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1556 FragmentManager fm
= getSupportFragmentManager();
1557 FragmentTransaction ft
= fm
.beginTransaction();
1558 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1561 private void requestForDownload(OCFile file
) {
1562 Account account
= getAccount();
1563 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1564 Intent i
= new Intent(this, FileDownloader
.class);
1565 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1566 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1571 private void sendDownloadedFile(){
1572 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1573 mWaitingToSend
= null
;
1578 * Requests the download of the received {@link OCFile} , updates the UI
1579 * to monitor the download progress and prepares the activity to send the file
1580 * when the download finishes.
1582 * @param file {@link OCFile} to download and preview.
1584 public void startDownloadForSending(OCFile file
) {
1585 mWaitingToSend
= file
;
1586 requestForDownload(mWaitingToSend
);
1587 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1588 updateFragmentsVisibility(hasSecondFragment
);
1592 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1594 * @param file Image {@link OCFile} to show.
1596 public void startImagePreview(OCFile file
) {
1597 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1598 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1599 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1600 startActivity(showDetailsIntent
);
1605 * Stars the preview of an already down media {@link OCFile}.
1607 * @param file Media {@link OCFile} to preview.
1608 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1609 * @param autoplay When 'true', the playback will start without user interactions.
1611 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1612 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1613 setSecondFragment(mediaFragment
);
1614 updateFragmentsVisibility(true
);
1615 updateNavigationElementsInActionBar(file
);
1620 * Requests the download of the received {@link OCFile} , updates the UI
1621 * to monitor the download progress and prepares the activity to preview
1622 * or open the file when the download finishes.
1624 * @param file {@link OCFile} to download and preview.
1626 public void startDownloadForPreview(OCFile file
) {
1627 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1628 setSecondFragment(detailFragment
);
1629 mWaitingToPreview
= file
;
1630 requestForDownload();
1631 updateFragmentsVisibility(true
);
1632 updateNavigationElementsInActionBar(file
);
1637 public void cancelTransference(OCFile file
) {
1638 getFileOperationsHelper().cancelTransference(file
);
1639 if (mWaitingToPreview
!= null
&&
1640 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1641 mWaitingToPreview
= null
;
1643 if (mWaitingToSend
!= null
&&
1644 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1645 mWaitingToSend
= null
;
1647 onTransferStateChanged(file
, false
, false
);