1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.util
.Log
;
52 import android
.view
.View
;
53 import android
.view
.ViewGroup
;
54 import android
.widget
.ArrayAdapter
;
55 import android
.widget
.TextView
;
56 import android
.widget
.Toast
;
58 import com
.actionbarsherlock
.app
.ActionBar
;
59 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
60 import com
.actionbarsherlock
.view
.Menu
;
61 import com
.actionbarsherlock
.view
.MenuInflater
;
62 import com
.actionbarsherlock
.view
.MenuItem
;
63 import com
.actionbarsherlock
.view
.Window
;
64 import com
.owncloud
.android
.MainApp
;
65 import com
.owncloud
.android
.R
;
66 import com
.owncloud
.android
.datamodel
.OCFile
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
81 import com
.owncloud
.android
.operations
.CreateShareOperation
;
82 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
83 import com
.owncloud
.android
.operations
.RenameFileOperation
;
84 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
86 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
87 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
88 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
89 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
92 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
99 import com
.owncloud
.android
.utils
.DisplayUtils
;
100 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
101 import com
.owncloud
.android
.utils
.Log_OC
;
105 * Displays, what files the user has available in his ownCloud.
107 * @author Bartek Przybylski
108 * @author David A. Velasco
111 public class FileDisplayActivity
extends HookActivity
implements
112 FileFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
{
114 private ArrayAdapter
<String
> mDirectories
;
116 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
117 private UploadFinishReceiver mUploadFinishReceiver
;
118 private DownloadFinishReceiver mDownloadFinishReceiver
;
119 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
121 private boolean mDualPane
;
122 private View mLeftFragmentContainer
;
123 private View mRightFragmentContainer
;
125 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
126 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
127 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
129 public static final int DIALOG_SHORT_WAIT
= 0;
130 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
131 private static final int DIALOG_CERT_NOT_SAVED
= 2;
133 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
135 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
136 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
138 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
140 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
143 private OCFile mWaitingToPreview
;
145 private boolean mSyncInProgress
= false
;
147 private String DIALOG_UNTRUSTED_CERT
;
149 private OCFile mWaitingToSend
;
152 protected void onCreate(Bundle savedInstanceState
) {
153 Log_OC
.d(TAG
, "onCreate() start");
154 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
156 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
158 // PIN CODE request ; best location is to decide, let's try this first
159 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
161 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
165 /// grant that FileObserverService is watching favourite files
166 if (savedInstanceState
== null
) {
167 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
168 startService(initObserversIntent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
174 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
175 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
178 mWaitingToPreview
= null
;
179 mSyncInProgress
= false
;
180 mWaitingToSend
= null
;
185 // Inflate and set the layout view
186 setContentView(R
.layout
.files
);
187 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
188 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
189 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
190 if (savedInstanceState
== null
) {
191 createMinFragments();
195 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
196 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
197 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
199 Log_OC
.d(TAG
, "onCreate() end");
203 protected void onStart() {
205 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
209 protected void onDestroy() {
214 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
217 protected void onAccountSet(boolean stateWasRecovered
) {
218 super.onAccountSet(stateWasRecovered
);
219 if (getAccount() != null
) {
220 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
221 OCFile file
= getFile();
222 // get parent from path
223 String parentPath
= "";
225 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
226 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
227 // get parent from path
228 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
229 if (getStorageManager().getFileByPath(parentPath
) == null
)
230 file
= null
; // not able to know the directory where the file is uploading
232 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
236 // fall back to root folder
237 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
240 setNavigationListWithFolder(file
);
242 if (!stateWasRecovered
) {
243 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
244 initFragmentsWithFile();
245 if (file
.isFolder()) {
246 startSyncFolderOperation(file
);
250 updateFragmentsVisibility(!file
.isFolder());
251 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
257 private void setNavigationListWithFolder(OCFile file
) {
258 mDirectories
.clear();
259 OCFile fileIt
= file
;
261 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
262 if (fileIt
.isFolder()) {
263 mDirectories
.add(fileIt
.getFileName());
265 // get parent from path
266 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
267 fileIt
= getStorageManager().getFileByPath(parentPath
);
269 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
273 private void createMinFragments() {
274 OCFileListFragment listOfFiles
= new OCFileListFragment();
275 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
276 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
277 transaction
.commit();
280 private void initFragmentsWithFile() {
281 if (getAccount() != null
&& getFile() != null
) {
283 OCFileListFragment listOfFiles
= getListOfFilesFragment();
284 if (listOfFiles
!= null
) {
285 listOfFiles
.listDirectory(getCurrentDir());
287 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
291 OCFile file
= getFile();
292 Fragment secondFragment
= chooseInitialSecondFragment(file
);
293 if (secondFragment
!= null
) {
294 setSecondFragment(secondFragment
);
295 updateFragmentsVisibility(true
);
296 updateNavigationElementsInActionBar(file
);
299 cleanSecondFragment();
303 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
304 if (getAccount() == null
) {
305 Log
.wtf(TAG
, "\t account is NULL");
307 if (getFile() == null
) {
308 Log
.wtf(TAG
, "\t file is NULL");
313 private Fragment
chooseInitialSecondFragment(OCFile file
) {
314 Fragment secondFragment
= null
;
315 if (file
!= null
&& !file
.isFolder()) {
316 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
317 && file
.getLastSyncDateForProperties() > 0 // temporal fix
319 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
320 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
321 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
324 secondFragment
= new FileDetailFragment(file
, getAccount());
327 return secondFragment
;
332 * Replaces the second fragment managed by the activity with the received as
335 * Assumes never will be more than two fragments managed at the same time.
337 * @param fragment New second Fragment to set.
339 private void setSecondFragment(Fragment fragment
) {
340 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
341 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
342 transaction
.commit();
346 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
348 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
349 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
351 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
352 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
355 } else if (existsSecondFragment
) {
356 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
357 mLeftFragmentContainer
.setVisibility(View
.GONE
);
359 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
360 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
364 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
368 mRightFragmentContainer
.setVisibility(View
.GONE
);
374 private OCFileListFragment
getListOfFilesFragment() {
375 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
376 if (listOfFiles
!= null
) {
377 return (OCFileListFragment
)listOfFiles
;
379 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
383 public FileFragment
getSecondFragment() {
384 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
385 if (second
!= null
) {
386 return (FileFragment
)second
;
391 protected void cleanSecondFragment() {
392 Fragment second
= getSecondFragment();
393 if (second
!= null
) {
394 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
398 updateFragmentsVisibility(false
);
399 updateNavigationElementsInActionBar(null
);
402 protected void refreshListOfFilesFragment() {
403 OCFileListFragment fileListFragment
= getListOfFilesFragment();
404 if (fileListFragment
!= null
) {
405 fileListFragment
.listDirectory();
409 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
410 FileFragment secondFragment
= getSecondFragment();
411 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
412 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
413 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
414 OCFile fileInFragment
= detailsFragment
.getFile();
415 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
416 // the user browsed to other file ; forget the automatic preview
417 mWaitingToPreview
= null
;
419 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
420 // grant that the right panel updates the progress bar
421 detailsFragment
.listenForTransferProgress();
422 detailsFragment
.updateFileDetails(true
, false
);
424 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
425 // update the right panel
426 boolean detailsFragmentChanged
= false
;
429 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
430 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
431 startMediaPreview(mWaitingToPreview
, 0, true
);
432 detailsFragmentChanged
= true
;
434 getFileOperationsHelper().openFile(mWaitingToPreview
);
437 mWaitingToPreview
= null
;
439 if (!detailsFragmentChanged
) {
440 detailsFragment
.updateFileDetails(false
, (success
));
447 public boolean onCreateOptionsMenu(Menu menu
) {
448 MenuInflater inflater
= getSherlock().getMenuInflater();
449 inflater
.inflate(R
.menu
.main_menu
, menu
);
454 public boolean onOptionsItemSelected(MenuItem item
) {
455 boolean retval
= true
;
456 switch (item
.getItemId()) {
457 case R
.id
.action_create_dir
: {
458 CreateFolderDialogFragment dialog
=
459 CreateFolderDialogFragment
.newInstance(getCurrentDir());
460 dialog
.show(getSupportFragmentManager(), "createdirdialog");
463 case R
.id
.action_sync_account
: {
464 startSynchronization();
467 case R
.id
.action_upload
: {
468 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
471 case R
.id
.action_settings
: {
472 Intent settingsIntent
= new Intent(this, Preferences
.class);
473 startActivity(settingsIntent
);
476 case android
.R
.id
.home
: {
477 FileFragment second
= getSecondFragment();
478 OCFile currentDir
= getCurrentDir();
479 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
480 (second
!= null
&& second
.getFile() != null
)) {
487 retval
= super.onOptionsItemSelected(item
);
492 private void startSynchronization() {
493 Log_OC
.e(TAG
, "Got to start sync");
494 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
495 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
496 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
497 Bundle bundle
= new Bundle();
498 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
499 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
500 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
501 ContentResolver
.requestSync(
503 MainApp
.getAuthority(), bundle
);
505 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
506 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
507 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
508 builder
.setExpedited(true
);
509 builder
.setManual(true
);
511 SyncRequest request
= builder
.build();
512 ContentResolver
.requestSync(request
);
518 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
519 if (itemPosition
!= 0) {
520 String targetPath
= "";
521 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
522 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
524 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
525 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
526 if (targetFolder
!= null
) {
527 browseTo(targetFolder
);
530 // the next operation triggers a new call to this method, but it's necessary to
531 // ensure that the name exposed in the action bar is the current directory when the
532 // user selected it in the navigation list
533 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
534 getSupportActionBar().setSelectedNavigationItem(0);
540 * Called, when the user selected something for uploading
542 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
543 super.onActivityResult(requestCode
, resultCode
, data
);
545 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
546 requestSimpleUpload(data
, resultCode
);
548 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
549 requestMultipleUpload(data
, resultCode
);
554 private void requestMultipleUpload(Intent data
, int resultCode
) {
555 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
556 if (filePaths
!= null
) {
557 String
[] remotePaths
= new String
[filePaths
.length
];
558 String remotePathBase
= "";
559 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
560 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
562 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
563 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
564 for (int j
= 0; j
< remotePaths
.length
; j
++) {
565 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
568 Intent i
= new Intent(this, FileUploader
.class);
569 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
570 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
571 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
572 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
573 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
574 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
578 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
579 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
586 private void requestSimpleUpload(Intent data
, int resultCode
) {
587 String filepath
= null
;
589 Uri selectedImageUri
= data
.getData();
591 String filemanagerstring
= selectedImageUri
.getPath();
592 String selectedImagePath
= getPath(selectedImageUri
);
594 if (selectedImagePath
!= null
)
595 filepath
= selectedImagePath
;
597 filepath
= filemanagerstring
;
599 } catch (Exception e
) {
600 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
604 if (filepath
== null
) {
605 Log_OC
.e(TAG
, "Couldnt resolve path to file");
606 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
612 Intent i
= new Intent(this, FileUploader
.class);
613 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
615 String remotepath
= new String();
616 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
617 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
619 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
620 remotepath
+= OCFile
.PATH_SEPARATOR
;
621 remotepath
+= new File(filepath
).getName();
623 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
624 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
625 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
626 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
627 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
632 public void onBackPressed() {
633 OCFileListFragment listOfFiles
= getListOfFilesFragment();
634 if (mDualPane
|| getSecondFragment() == null
) {
635 if (listOfFiles
!= null
) { // should never be null, indeed
636 if (mDirectories
.getCount() <= 1) {
640 int levelsUp
= listOfFiles
.onBrowseUp();
641 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
646 if (listOfFiles
!= null
) { // should never be null, indeed
647 setFile(listOfFiles
.getCurrentFile());
649 cleanSecondFragment();
654 protected void onSaveInstanceState(Bundle outState
) {
655 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
656 Log_OC
.e(TAG
, "onSaveInstanceState() start");
657 super.onSaveInstanceState(outState
);
658 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
659 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
660 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
661 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
663 Log_OC
.d(TAG
, "onSaveInstanceState() end");
669 protected void onResume() {
671 Log_OC
.e(TAG
, "onResume() start");
673 // refresh list of files
674 refreshListOfFilesFragment();
676 // Listen for sync messages
677 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
678 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
679 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
680 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
681 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
682 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
683 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
684 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
686 // Listen for upload messages
687 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
688 mUploadFinishReceiver
= new UploadFinishReceiver();
689 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
691 // Listen for download messages
692 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
693 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
694 mDownloadFinishReceiver
= new DownloadFinishReceiver();
695 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
697 Log_OC
.d(TAG
, "onResume() end");
702 protected void onPause() {
703 Log_OC
.e(TAG
, "onPause() start");
704 if (mSyncBroadcastReceiver
!= null
) {
705 unregisterReceiver(mSyncBroadcastReceiver
);
706 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
707 mSyncBroadcastReceiver
= null
;
709 if (mUploadFinishReceiver
!= null
) {
710 unregisterReceiver(mUploadFinishReceiver
);
711 mUploadFinishReceiver
= null
;
713 if (mDownloadFinishReceiver
!= null
) {
714 unregisterReceiver(mDownloadFinishReceiver
);
715 mDownloadFinishReceiver
= null
;
719 Log_OC
.d(TAG
, "onPause() end");
725 protected Dialog
onCreateDialog(int id
) {
726 Dialog dialog
= null
;
727 AlertDialog
.Builder builder
;
729 case DIALOG_SHORT_WAIT
: {
730 ProgressDialog working_dialog
= new ProgressDialog(this);
731 working_dialog
.setMessage(getResources().getString(
732 R
.string
.wait_a_moment
));
733 working_dialog
.setIndeterminate(true
);
734 working_dialog
.setCancelable(false
);
735 dialog
= working_dialog
;
738 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
741 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
742 getString(R
.string
.actionbar_upload_from_apps
) };
744 builder
= new AlertDialog
.Builder(this);
745 builder
.setTitle(R
.string
.actionbar_upload
);
746 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
747 public void onClick(DialogInterface dialog
, int item
) {
750 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
751 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
752 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
754 // TODO create and handle new fragment
755 // LocalFileListFragment
757 } else if (item
== 1) {
758 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
759 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
760 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
761 ACTION_SELECT_CONTENT_FROM_APPS
);
765 dialog
= builder
.create();
768 case DIALOG_CERT_NOT_SAVED
: {
769 builder
= new AlertDialog
.Builder(this);
770 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
771 builder
.setCancelable(false
);
772 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
774 public void onClick(DialogInterface dialog
, int which
) {
778 dialog
= builder
.create();
790 * Translates a content URI of an image to a physical path
792 * @param uri The URI to resolve
793 * @return The path to the image or null if it could not be found
795 public String
getPath(Uri uri
) {
796 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
797 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
798 if (cursor
!= null
) {
799 int column_index
= cursor
800 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
801 cursor
.moveToFirst();
802 return cursor
.getString(column_index
);
808 * Pushes a directory to the drop down list
809 * @param directory to push
810 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
812 public void pushDirname(OCFile directory
) {
813 if(!directory
.isFolder()){
814 throw new IllegalArgumentException("Only directories may be pushed!");
816 mDirectories
.insert(directory
.getFileName(), 0);
821 * Pops a directory name from the drop down list
822 * @return True, unless the stack is empty
824 public boolean popDirname() {
825 mDirectories
.remove(mDirectories
.getItem(0));
826 return !mDirectories
.isEmpty();
829 // Custom array adapter to override text colors
830 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
832 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
836 public View
getView(int position
, View convertView
, ViewGroup parent
) {
837 View v
= super.getView(position
, convertView
, parent
);
839 ((TextView
) v
).setTextColor(getResources().getColorStateList(
840 android
.R
.color
.white
));
842 fixRoot((TextView
) v
);
846 public View
getDropDownView(int position
, View convertView
,
848 View v
= super.getDropDownView(position
, convertView
, parent
);
850 ((TextView
) v
).setTextColor(getResources().getColorStateList(
851 android
.R
.color
.white
));
853 fixRoot((TextView
) v
);
857 private void fixRoot(TextView v
) {
858 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
859 v
.setText(R
.string
.default_display_name_for_root_folder
);
865 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
868 * {@link BroadcastReceiver} to enable syncing feedback in UI
871 public void onReceive(Context context
, Intent intent
) {
873 String event
= intent
.getAction();
874 Log_OC
.d(TAG
, "Received broadcast " + event
);
875 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
876 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
877 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
878 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
882 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
883 mSyncInProgress
= true
;
886 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
887 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
889 if (currentDir
== null
) {
890 // current folder was removed from the server
891 Toast
.makeText( FileDisplayActivity
.this,
892 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
898 if (currentFile
== null
&& !getFile().isFolder()) {
899 // currently selected file was removed in the server, and now we know it
900 cleanSecondFragment();
901 currentFile
= currentDir
;
904 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
905 OCFileListFragment fileListFragment
= getListOfFilesFragment();
906 if (fileListFragment
!= null
) {
907 fileListFragment
.listDirectory(currentDir
);
910 setFile(currentFile
);
913 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
915 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
917 /// TODO refactor and make common
918 synchResult
!= null
&& !synchResult
.isSuccess() &&
919 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
920 synchResult
.isIdPRedirection() ||
921 (synchResult
.isException() && synchResult
.getException()
922 instanceof AuthenticatorException
))) {
924 OwnCloudClient client
= null
;
926 OwnCloudAccount ocAccount
=
927 new OwnCloudAccount(getAccount(), context
);
928 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
929 removeClientFor(ocAccount
));
930 // TODO get rid of these exceptions
931 } catch (AccountNotFoundException e
) {
933 } catch (AuthenticatorException e
) {
935 } catch (OperationCanceledException e
) {
937 } catch (IOException e
) {
941 if (client
!= null
) {
942 OwnCloudCredentials cred
= client
.getCredentials();
944 AccountManager am
= AccountManager
.get(context
);
945 if (cred
.authTokenExpires()) {
946 am
.invalidateAuthToken(
951 am
.clearPassword(getAccount());
956 requestCredentialsUpdate();
960 removeStickyBroadcast(intent
);
961 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
962 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
966 if (synchResult
!= null
) {
967 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
968 mLastSslUntrustedServerResult
= synchResult
;
971 } catch (RuntimeException e
) {
972 // avoid app crashes after changing the serial id of RemoteOperationResult
973 // in owncloud library with broadcast notifications pending to process
974 removeStickyBroadcast(intent
);
981 * Once the file upload has finished -> update view
983 private class UploadFinishReceiver
extends BroadcastReceiver
{
985 * Once the file upload has finished -> update view
986 * @author David A. Velasco
987 * {@link BroadcastReceiver} to enable upload feedback in UI
990 public void onReceive(Context context
, Intent intent
) {
992 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
993 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
994 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
995 OCFile currentDir
= getCurrentDir();
996 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
997 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
999 if (sameAccount
&& isDescendant
) {
1000 refreshListOfFilesFragment();
1003 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1004 boolean renamedInUpload
= getFile().getRemotePath().
1005 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1006 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1008 FileFragment details
= getSecondFragment();
1009 boolean detailFragmentIsShown
= (details
!= null
&&
1010 details
instanceof FileDetailFragment
);
1012 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1013 if (uploadWasFine
) {
1014 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1016 if (renamedInUpload
) {
1017 String newName
= (new File(uploadedRemotePath
)).getName();
1018 Toast msg
= Toast
.makeText(
1021 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1026 if (uploadWasFine
|| getFile().fileExists()) {
1027 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1029 cleanSecondFragment();
1032 // Force the preview if the file is an image
1033 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1034 startImagePreview(getFile());
1035 } // TODO what about other kind of previews?
1039 if (intent
!= null
) {
1040 removeStickyBroadcast(intent
);
1050 * Class waiting for broadcast events from the {@link FielDownloader} service.
1052 * Updates the UI when a download is started or finished, provided that it is relevant for the
1055 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1057 public void onReceive(Context context
, Intent intent
) {
1059 boolean sameAccount
= isSameAccount(context
, intent
);
1060 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1061 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1063 if (sameAccount
&& isDescendant
) {
1064 refreshListOfFilesFragment();
1065 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1068 if (mWaitingToSend
!= null
) {
1069 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1070 if (mWaitingToSend
.isDown()) {
1071 sendDownloadedFile();
1076 if (intent
!= null
) {
1077 removeStickyBroadcast(intent
);
1082 private boolean isDescendant(String downloadedRemotePath
) {
1083 OCFile currentDir
= getCurrentDir();
1084 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1087 private boolean isSameAccount(Context context
, Intent intent
) {
1088 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1089 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1094 public void browseToRoot() {
1095 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1096 if (listOfFiles
!= null
) { // should never be null, indeed
1097 while (mDirectories
.getCount() > 1) {
1100 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1101 listOfFiles
.listDirectory(root
);
1102 setFile(listOfFiles
.getCurrentFile());
1103 startSyncFolderOperation(root
);
1105 cleanSecondFragment();
1109 public void browseTo(OCFile folder
) {
1110 if (folder
== null
|| !folder
.isFolder()) {
1111 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1113 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1114 if (listOfFiles
!= null
) {
1115 setNavigationListWithFolder(folder
);
1116 listOfFiles
.listDirectory(folder
);
1117 setFile(listOfFiles
.getCurrentFile());
1118 startSyncFolderOperation(folder
);
1120 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1122 cleanSecondFragment();
1129 * Updates action bar and second fragment, if in dual pane mode.
1132 public void onBrowsedDownTo(OCFile directory
) {
1133 pushDirname(directory
);
1134 cleanSecondFragment();
1137 startSyncFolderOperation(directory
);
1142 * Shows the information of the {@link OCFile} received as a
1143 * parameter in the second fragment.
1145 * @param file {@link OCFile} whose details will be shown
1148 public void showDetails(OCFile file
) {
1149 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1150 setSecondFragment(detailFragment
);
1151 updateFragmentsVisibility(true
);
1152 updateNavigationElementsInActionBar(file
);
1160 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1161 ActionBar actionBar
= getSupportActionBar();
1162 if (chosenFile
== null
|| mDualPane
) {
1163 // only list of files - set for browsing through folders
1164 OCFile currentDir
= getCurrentDir();
1165 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1166 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1167 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1169 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1171 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1172 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1175 actionBar
.setDisplayHomeAsUpEnabled(true
);
1176 actionBar
.setDisplayShowTitleEnabled(true
);
1177 actionBar
.setTitle(chosenFile
.getFileName());
1178 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1184 protected ServiceConnection
newTransferenceServiceConnection() {
1185 return new ListServiceConnection();
1188 /** Defines callbacks for service binding, passed to bindService() */
1189 private class ListServiceConnection
implements ServiceConnection
{
1192 public void onServiceConnected(ComponentName component
, IBinder service
) {
1193 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1194 Log_OC
.d(TAG
, "Download service connected");
1195 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1196 if (mWaitingToPreview
!= null
)
1197 if (getStorageManager() != null
) {
1198 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1199 if (!mWaitingToPreview
.isDown()) {
1200 requestForDownload();
1204 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1205 Log_OC
.d(TAG
, "Upload service connected");
1206 mUploaderBinder
= (FileUploaderBinder
) service
;
1210 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1211 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1212 if (listOfFiles
!= null
) {
1213 listOfFiles
.listDirectory();
1215 FileFragment secondFragment
= getSecondFragment();
1216 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1217 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1218 detailFragment
.listenForTransferProgress();
1219 detailFragment
.updateFileDetails(false
, false
);
1224 public void onServiceDisconnected(ComponentName component
) {
1225 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1226 Log_OC
.d(TAG
, "Download service disconnected");
1227 mDownloaderBinder
= null
;
1228 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1229 Log_OC
.d(TAG
, "Upload service disconnected");
1230 mUploaderBinder
= null
;
1238 * Launch an intent to request the PIN code to the user before letting him use the app
1240 private void requestPinCode() {
1241 boolean pinStart
= false
;
1242 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1243 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1245 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1246 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1253 public void onSavedCertificate() {
1254 startSyncFolderOperation(getCurrentDir());
1259 public void onFailedSavingCertificate() {
1260 showDialog(DIALOG_CERT_NOT_SAVED
);
1264 public void onCancelCertificate() {
1269 * Updates the view associated to the activity after the finish of some operation over files
1270 * in the current account.
1272 * @param operation Removal operation performed.
1273 * @param result Result of the removal.
1276 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1277 super.onRemoteOperationFinish(operation
, result
);
1279 if (operation
instanceof RemoveFileOperation
) {
1280 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1282 } else if (operation
instanceof RenameFileOperation
) {
1283 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1285 } else if (operation
instanceof SynchronizeFileOperation
) {
1286 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1288 } else if (operation
instanceof CreateFolderOperation
) {
1289 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1291 } else if (operation
instanceof CreateShareOperation
) {
1292 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1294 } else if (operation
instanceof UnshareLinkOperation
) {
1295 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1302 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1303 if (result
.isSuccess()) {
1304 refreshShowDetails();
1305 refreshListOfFilesFragment();
1310 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1311 if (result
.isSuccess()) {
1312 refreshShowDetails();
1313 refreshListOfFilesFragment();
1315 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1316 cleanSecondFragment();
1317 refreshListOfFilesFragment();
1321 private void refreshShowDetails() {
1322 FileFragment details
= getSecondFragment();
1323 if (details
!= null
) {
1324 OCFile file
= details
.getFile();
1326 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1327 if (details
instanceof PreviewMediaFragment
) {
1328 // Refresh OCFile of the fragment
1329 ((PreviewMediaFragment
) details
).updateFile(file
);
1334 invalidateOptionsMenu();
1339 * Updates the view associated to the activity after the finish of an operation trying to remove a
1342 * @param operation Removal operation performed.
1343 * @param result Result of the removal.
1345 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1346 dismissLoadingDialog();
1348 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1352 if (result
.isSuccess()) {
1353 OCFile removedFile
= operation
.getFile();
1354 FileFragment second
= getSecondFragment();
1355 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1356 if (second
instanceof PreviewMediaFragment
) {
1357 ((PreviewMediaFragment
)second
).stopPreview(true
);
1359 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1360 cleanSecondFragment();
1362 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1363 refreshListOfFilesFragment();
1365 invalidateOptionsMenu();
1367 if (result
.isSslRecoverableException()) {
1368 mLastSslUntrustedServerResult
= result
;
1369 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1376 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1378 * @param operation Creation operation performed.
1379 * @param result Result of the creation.
1381 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1382 if (result
.isSuccess()) {
1383 dismissLoadingDialog();
1384 refreshListOfFilesFragment();
1386 dismissLoadingDialog();
1388 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1389 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1393 } catch (NotFoundException e
) {
1394 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1401 * Updates the view associated to the activity after the finish of an operation trying to rename a
1404 * @param operation Renaming operation performed.
1405 * @param result Result of the renaming.
1407 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1408 dismissLoadingDialog();
1409 OCFile renamedFile
= operation
.getFile();
1410 if (result
.isSuccess()) {
1411 FileFragment details
= getSecondFragment();
1412 if (details
!= null
) {
1413 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1414 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1415 showDetails(renamedFile
);
1417 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1418 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1419 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1420 int position
= ((PreviewMediaFragment
)details
).getPosition();
1421 startMediaPreview(renamedFile
, position
, true
);
1423 getFileOperationsHelper().openFile(renamedFile
);
1428 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1429 refreshListOfFilesFragment();
1433 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1437 if (result
.isSslRecoverableException()) {
1438 mLastSslUntrustedServerResult
= result
;
1439 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1444 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1445 dismissLoadingDialog();
1446 OCFile syncedFile
= operation
.getLocalFile();
1447 if (!result
.isSuccess()) {
1448 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1449 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1450 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1451 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1457 if (operation
.transferWasRequested()) {
1458 onTransferStateChanged(syncedFile
, true
, true
);
1461 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1473 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1474 refreshListOfFilesFragment();
1475 FileFragment details
= getSecondFragment();
1476 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1477 if (downloading
|| uploading
) {
1478 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1480 if (!file
.fileExists()) {
1481 cleanSecondFragment();
1483 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1491 private void requestForDownload() {
1492 Account account
= getAccount();
1493 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1494 Intent i
= new Intent(this, FileDownloader
.class);
1495 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1496 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1502 private OCFile
getCurrentDir() {
1503 OCFile file
= getFile();
1505 if (file
.isFolder()) {
1507 } else if (getStorageManager() != null
) {
1508 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1509 return getStorageManager().getFileByPath(parentPath
);
1515 public void startSyncFolderOperation(OCFile folder
) {
1516 long currentSyncTime
= System
.currentTimeMillis();
1518 mSyncInProgress
= true
;
1520 // perform folder synchronization
1521 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1524 getFileOperationsHelper().isSharedSupported(),
1525 getStorageManager(),
1527 getApplicationContext()
1529 synchFolderOp
.execute(getAccount(), this, null
, null
);
1531 setSupportProgressBarIndeterminateVisibility(true
);
1535 * Show untrusted cert dialog
1537 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1538 // Show a dialog with the certificate info
1539 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1540 FragmentManager fm
= getSupportFragmentManager();
1541 FragmentTransaction ft
= fm
.beginTransaction();
1542 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1545 private void requestForDownload(OCFile file
) {
1546 Account account
= getAccount();
1547 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1548 Intent i
= new Intent(this, FileDownloader
.class);
1549 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1550 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1555 private void sendDownloadedFile(){
1556 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1557 mWaitingToSend
= null
;
1562 * Requests the download of the received {@link OCFile} , updates the UI
1563 * to monitor the download progress and prepares the activity to send the file
1564 * when the download finishes.
1566 * @param file {@link OCFile} to download and preview.
1568 public void startDownloadForSending(OCFile file
) {
1569 mWaitingToSend
= file
;
1570 requestForDownload(mWaitingToSend
);
1571 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1572 updateFragmentsVisibility(hasSecondFragment
);
1576 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1578 * @param file Image {@link OCFile} to show.
1580 public void startImagePreview(OCFile file
) {
1581 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1582 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1583 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1584 startActivity(showDetailsIntent
);
1589 * Stars the preview of an already down media {@link OCFile}.
1591 * @param file Media {@link OCFile} to preview.
1592 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1593 * @param autoplay When 'true', the playback will start without user interactions.
1595 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1596 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1597 setSecondFragment(mediaFragment
);
1598 updateFragmentsVisibility(true
);
1599 updateNavigationElementsInActionBar(file
);
1604 * Requests the download of the received {@link OCFile} , updates the UI
1605 * to monitor the download progress and prepares the activity to preview
1606 * or open the file when the download finishes.
1608 * @param file {@link OCFile} to download and preview.
1610 public void startDownloadForPreview(OCFile file
) {
1611 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1612 setSecondFragment(detailFragment
);
1613 mWaitingToPreview
= file
;
1614 requestForDownload();
1615 updateFragmentsVisibility(true
);
1616 updateNavigationElementsInActionBar(file
);
1621 public void cancelTransference(OCFile file
) {
1622 getFileOperationsHelper().cancelTransference(file
);
1623 if (mWaitingToPreview
!= null
&&
1624 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1625 mWaitingToPreview
= null
;
1627 if (mWaitingToSend
!= null
&&
1628 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1629 mWaitingToSend
= null
;
1631 onTransferStateChanged(file
, false
, false
);