1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 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
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.Dialog
;
26 import android
.app
.ProgressDialog
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.ComponentName
;
29 import android
.content
.ContentResolver
;
30 import android
.content
.Context
;
31 import android
.content
.DialogInterface
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.content
.SyncRequest
;
37 import android
.content
.res
.Resources
.NotFoundException
;
38 import android
.database
.Cursor
;
39 import android
.net
.Uri
;
40 import android
.os
.Bundle
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.provider
.MediaStore
;
44 import android
.support
.v4
.app
.Fragment
;
45 import android
.support
.v4
.app
.FragmentManager
;
46 import android
.support
.v4
.app
.FragmentTransaction
;
47 //import android.support.v4.content.LocalBroadcastManager;
48 import android
.util
.Log
;
49 import android
.view
.View
;
50 import android
.view
.ViewGroup
;
51 import android
.widget
.ArrayAdapter
;
52 import android
.widget
.TextView
;
53 import android
.widget
.Toast
;
55 import com
.actionbarsherlock
.app
.ActionBar
;
56 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
57 import com
.actionbarsherlock
.view
.Menu
;
58 import com
.actionbarsherlock
.view
.MenuInflater
;
59 import com
.actionbarsherlock
.view
.MenuItem
;
60 import com
.actionbarsherlock
.view
.Window
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.datamodel
.OCFile
;
64 import com
.owncloud
.android
.files
.services
.FileDownloader
;
65 import com
.owncloud
.android
.files
.services
.FileObserverService
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
69 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
71 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
75 import com
.owncloud
.android
.operations
.CreateShareOperation
;
76 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
77 import com
.owncloud
.android
.operations
.RenameFileOperation
;
78 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
79 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
80 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
81 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
82 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
83 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
85 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
86 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
87 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
88 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
89 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
92 import com
.owncloud
.android
.utils
.DisplayUtils
;
93 import com
.owncloud
.android
.utils
.Log_OC
;
97 * Displays, what files the user has available in his ownCloud.
99 * @author Bartek Przybylski
100 * @author David A. Velasco
103 public class FileDisplayActivity
extends HookActivity
implements
104 FileFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
{
106 private ArrayAdapter
<String
> mDirectories
;
108 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
109 private UploadFinishReceiver mUploadFinishReceiver
;
110 private DownloadFinishReceiver mDownloadFinishReceiver
;
111 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
113 private boolean mDualPane
;
114 private View mLeftFragmentContainer
;
115 private View mRightFragmentContainer
;
117 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
118 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
119 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
121 public static final int DIALOG_SHORT_WAIT
= 0;
122 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
123 private static final int DIALOG_CERT_NOT_SAVED
= 2;
125 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
127 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
128 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
130 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
132 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
133 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
135 private OCFile mWaitingToPreview
;
137 private boolean mSyncInProgress
= false
;
139 private String DIALOG_UNTRUSTED_CERT
;
141 private OCFile mWaitingToSend
;
144 protected void onCreate(Bundle savedInstanceState
) {
145 Log_OC
.d(TAG
, "onCreate() start");
146 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
148 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
150 // PIN CODE request ; best location is to decide, let's try this first
151 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
153 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
158 Intent observer_intent
= new Intent(this, FileObserverService
.class);
159 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
160 startService(observer_intent
);
162 /// Load of saved instance state
163 if(savedInstanceState
!= null
) {
164 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
165 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
166 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
169 mWaitingToPreview
= null
;
170 mSyncInProgress
= false
;
171 mWaitingToSend
= null
;
176 // Inflate and set the layout view
177 setContentView(R
.layout
.files
);
178 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
179 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
180 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
181 if (savedInstanceState
== null
) {
182 createMinFragments();
184 Log_OC
.d(TAG
, "Init the secondFragment again");
186 initFragmentsWithFile();
191 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
192 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
193 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
195 Log_OC
.d(TAG
, "onCreate() end");
199 protected void onStart() {
201 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
205 protected void onDestroy() {
210 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
213 protected void onAccountSet(boolean stateWasRecovered
) {
214 super.onAccountSet(stateWasRecovered
);
215 if (getAccount() != null
) {
216 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
217 OCFile file
= getFile();
218 // get parent from path
219 String parentPath
= "";
221 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
222 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
223 // get parent from path
224 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
225 if (getStorageManager().getFileByPath(parentPath
) == null
)
226 file
= null
; // not able to know the directory where the file is uploading
228 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
232 // fall back to root folder
233 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
236 setNavigationListWithFolder(file
);
238 if (!stateWasRecovered
) {
239 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
240 initFragmentsWithFile();
241 if (file
.isFolder()) {
242 startSyncFolderOperation(file
);
246 updateFragmentsVisibility(!file
.isFolder());
247 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
253 private void setNavigationListWithFolder(OCFile file
) {
254 mDirectories
.clear();
255 OCFile fileIt
= file
;
257 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
258 if (fileIt
.isFolder()) {
259 mDirectories
.add(fileIt
.getFileName());
261 // get parent from path
262 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
263 fileIt
= getStorageManager().getFileByPath(parentPath
);
265 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
269 private void createMinFragments() {
270 OCFileListFragment listOfFiles
= new OCFileListFragment();
271 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
272 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
273 transaction
.commit();
276 private void initFragmentsWithFile() {
277 if (getAccount() != null
&& getFile() != null
) {
279 OCFileListFragment listOfFiles
= getListOfFilesFragment();
280 if (listOfFiles
!= null
) {
281 listOfFiles
.listDirectory(getCurrentDir());
283 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
287 OCFile file
= getFile();
288 Fragment secondFragment
= chooseInitialSecondFragment(file
);
289 if (secondFragment
!= null
) {
290 setSecondFragment(secondFragment
);
291 updateFragmentsVisibility(true
);
292 updateNavigationElementsInActionBar(file
);
295 cleanSecondFragment();
299 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
300 if (getAccount() == null
) {
301 Log
.wtf(TAG
, "\t account is NULL");
303 if (getFile() == null
) {
304 Log
.wtf(TAG
, "\t file is NULL");
309 private Fragment
chooseInitialSecondFragment(OCFile file
) {
310 Fragment secondFragment
= null
;
311 if (file
!= null
&& !file
.isFolder()) {
312 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
313 && file
.getLastSyncDateForProperties() > 0 // temporal fix
315 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
316 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
317 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
320 secondFragment
= new FileDetailFragment(file
, getAccount());
323 return secondFragment
;
328 * Replaces the second fragment managed by the activity with the received as
331 * Assumes never will be more than two fragments managed at the same time.
333 * @param fragment New second Fragment to set.
335 private void setSecondFragment(Fragment fragment
) {
336 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
337 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
338 transaction
.commit();
342 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
344 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
345 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
347 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
348 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
351 } else if (existsSecondFragment
) {
352 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
353 mLeftFragmentContainer
.setVisibility(View
.GONE
);
355 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
356 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
360 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
361 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
363 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
364 mRightFragmentContainer
.setVisibility(View
.GONE
);
370 private OCFileListFragment
getListOfFilesFragment() {
371 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
372 if (listOfFiles
!= null
) {
373 return (OCFileListFragment
)listOfFiles
;
375 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
379 public FileFragment
getSecondFragment() {
380 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
381 if (second
!= null
) {
382 return (FileFragment
)second
;
387 protected void cleanSecondFragment() {
388 Fragment second
= getSecondFragment();
389 if (second
!= null
) {
390 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
394 updateFragmentsVisibility(false
);
395 updateNavigationElementsInActionBar(null
);
398 protected void refreshListOfFilesFragment() {
399 OCFileListFragment fileListFragment
= getListOfFilesFragment();
400 if (fileListFragment
!= null
) {
401 fileListFragment
.listDirectory();
405 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
406 FileFragment secondFragment
= getSecondFragment();
407 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
408 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
409 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
410 OCFile fileInFragment
= detailsFragment
.getFile();
411 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
412 // the user browsed to other file ; forget the automatic preview
413 mWaitingToPreview
= null
;
415 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
416 // grant that the right panel updates the progress bar
417 detailsFragment
.listenForTransferProgress();
418 detailsFragment
.updateFileDetails(true
, false
);
420 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
421 // update the right panel
422 boolean detailsFragmentChanged
= false
;
425 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
426 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
427 startMediaPreview(mWaitingToPreview
, 0, true
);
428 detailsFragmentChanged
= true
;
430 getFileOperationsHelper().openFile(mWaitingToPreview
);
433 mWaitingToPreview
= null
;
435 if (!detailsFragmentChanged
) {
436 detailsFragment
.updateFileDetails(false
, (success
));
443 public boolean onCreateOptionsMenu(Menu menu
) {
444 MenuInflater inflater
= getSherlock().getMenuInflater();
445 inflater
.inflate(R
.menu
.main_menu
, menu
);
450 public boolean onOptionsItemSelected(MenuItem item
) {
451 boolean retval
= true
;
452 switch (item
.getItemId()) {
453 case R
.id
.action_create_dir
: {
454 CreateFolderDialogFragment dialog
=
455 CreateFolderDialogFragment
.newInstance(getCurrentDir());
456 dialog
.show(getSupportFragmentManager(), "createdirdialog");
459 case R
.id
.action_sync_account
: {
460 startSynchronization();
463 case R
.id
.action_upload
: {
464 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
467 case R
.id
.action_settings
: {
468 Intent settingsIntent
= new Intent(this, Preferences
.class);
469 startActivity(settingsIntent
);
472 case android
.R
.id
.home
: {
473 FileFragment second
= getSecondFragment();
474 OCFile currentDir
= getCurrentDir();
475 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
476 (second
!= null
&& second
.getFile() != null
)) {
483 retval
= super.onOptionsItemSelected(item
);
488 private void startSynchronization() {
489 Log_OC
.e(TAG
, "Got to start sync");
490 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
491 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
492 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
493 Bundle bundle
= new Bundle();
494 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
495 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
496 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
497 ContentResolver
.requestSync(
499 MainApp
.getAuthority(), bundle
);
501 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
502 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
503 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
504 builder
.setExpedited(true
);
505 builder
.setManual(true
);
507 SyncRequest request
= builder
.build();
508 ContentResolver
.requestSync(request
);
514 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
515 if (itemPosition
!= 0) {
516 String targetPath
= "";
517 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
518 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
520 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
521 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
522 if (targetFolder
!= null
) {
523 browseTo(targetFolder
);
526 // the next operation triggers a new call to this method, but it's necessary to
527 // ensure that the name exposed in the action bar is the current directory when the
528 // user selected it in the navigation list
529 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
530 getSupportActionBar().setSelectedNavigationItem(0);
536 * Called, when the user selected something for uploading
538 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
539 super.onActivityResult(requestCode
, resultCode
, data
);
541 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
542 requestSimpleUpload(data
, resultCode
);
544 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
545 requestMultipleUpload(data
, resultCode
);
550 private void requestMultipleUpload(Intent data
, int resultCode
) {
551 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
552 if (filePaths
!= null
) {
553 String
[] remotePaths
= new String
[filePaths
.length
];
554 String remotePathBase
= "";
555 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
556 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
558 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
559 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
560 for (int j
= 0; j
< remotePaths
.length
; j
++) {
561 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
564 Intent i
= new Intent(this, FileUploader
.class);
565 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
566 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
567 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
568 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
569 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
570 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
574 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
575 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
582 private void requestSimpleUpload(Intent data
, int resultCode
) {
583 String filepath
= null
;
585 Uri selectedImageUri
= data
.getData();
587 String filemanagerstring
= selectedImageUri
.getPath();
588 String selectedImagePath
= getPath(selectedImageUri
);
590 if (selectedImagePath
!= null
)
591 filepath
= selectedImagePath
;
593 filepath
= filemanagerstring
;
595 } catch (Exception e
) {
596 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
600 if (filepath
== null
) {
601 Log_OC
.e(TAG
, "Couldnt resolve path to file");
602 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
608 Intent i
= new Intent(this, FileUploader
.class);
609 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
611 String remotepath
= new String();
612 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
613 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
615 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
616 remotepath
+= OCFile
.PATH_SEPARATOR
;
617 remotepath
+= new File(filepath
).getName();
619 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
620 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
621 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
622 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
623 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
628 public void onBackPressed() {
629 OCFileListFragment listOfFiles
= getListOfFilesFragment();
630 if (mDualPane
|| getSecondFragment() == null
) {
631 if (listOfFiles
!= null
) { // should never be null, indeed
632 if (mDirectories
.getCount() <= 1) {
636 int levelsUp
= listOfFiles
.onBrowseUp();
637 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
642 if (listOfFiles
!= null
) { // should never be null, indeed
643 setFile(listOfFiles
.getCurrentFile());
645 cleanSecondFragment();
650 protected void onSaveInstanceState(Bundle outState
) {
651 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
652 Log_OC
.e(TAG
, "onSaveInstanceState() start");
653 super.onSaveInstanceState(outState
);
654 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
655 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
656 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
657 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
659 Log_OC
.d(TAG
, "onSaveInstanceState() end");
665 protected void onResume() {
667 Log_OC
.e(TAG
, "onResume() start");
669 // refresh list of files
670 refreshListOfFilesFragment();
672 // Listen for sync messages
673 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
674 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
675 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
676 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
677 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
678 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
679 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
680 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
682 // Listen for upload messages
683 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
684 mUploadFinishReceiver
= new UploadFinishReceiver();
685 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
687 // Listen for download messages
688 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
689 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
690 mDownloadFinishReceiver
= new DownloadFinishReceiver();
691 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
693 Log_OC
.d(TAG
, "onResume() end");
698 protected void onPause() {
699 Log_OC
.e(TAG
, "onPause() start");
700 if (mSyncBroadcastReceiver
!= null
) {
701 unregisterReceiver(mSyncBroadcastReceiver
);
702 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
703 mSyncBroadcastReceiver
= null
;
705 if (mUploadFinishReceiver
!= null
) {
706 unregisterReceiver(mUploadFinishReceiver
);
707 mUploadFinishReceiver
= null
;
709 if (mDownloadFinishReceiver
!= null
) {
710 unregisterReceiver(mDownloadFinishReceiver
);
711 mDownloadFinishReceiver
= null
;
715 Log_OC
.d(TAG
, "onPause() end");
721 protected Dialog
onCreateDialog(int id
) {
722 Dialog dialog
= null
;
723 AlertDialog
.Builder builder
;
725 case DIALOG_SHORT_WAIT
: {
726 ProgressDialog working_dialog
= new ProgressDialog(this);
727 working_dialog
.setMessage(getResources().getString(
728 R
.string
.wait_a_moment
));
729 working_dialog
.setIndeterminate(true
);
730 working_dialog
.setCancelable(false
);
731 dialog
= working_dialog
;
734 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
736 String
[] items
= null
;
738 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
739 getString(R
.string
.actionbar_upload_from_apps
),
740 getString(R
.string
.actionbar_failed_instant_upload
) };
742 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
743 getString(R
.string
.actionbar_upload_from_apps
) };
745 if (InstantUploadActivity
.IS_ENABLED
)
750 builder
= new AlertDialog
.Builder(this);
751 builder
.setTitle(R
.string
.actionbar_upload
);
752 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
753 public void onClick(DialogInterface dialog
, int item
) {
756 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
757 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
758 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
760 // TODO create and handle new fragment
761 // LocalFileListFragment
763 } else if (item
== 1) {
764 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
765 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
766 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
767 ACTION_SELECT_CONTENT_FROM_APPS
);
768 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
769 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
770 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
771 startActivity(action
);
775 dialog
= builder
.create();
778 case DIALOG_CERT_NOT_SAVED
: {
779 builder
= new AlertDialog
.Builder(this);
780 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
781 builder
.setCancelable(false
);
782 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
784 public void onClick(DialogInterface dialog
, int which
) {
788 dialog
= builder
.create();
800 * Translates a content URI of an image to a physical path
802 * @param uri The URI to resolve
803 * @return The path to the image or null if it could not be found
805 public String
getPath(Uri uri
) {
806 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
807 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
808 if (cursor
!= null
) {
809 int column_index
= cursor
810 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
811 cursor
.moveToFirst();
812 return cursor
.getString(column_index
);
818 * Pushes a directory to the drop down list
819 * @param directory to push
820 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
822 public void pushDirname(OCFile directory
) {
823 if(!directory
.isFolder()){
824 throw new IllegalArgumentException("Only directories may be pushed!");
826 mDirectories
.insert(directory
.getFileName(), 0);
831 * Pops a directory name from the drop down list
832 * @return True, unless the stack is empty
834 public boolean popDirname() {
835 mDirectories
.remove(mDirectories
.getItem(0));
836 return !mDirectories
.isEmpty();
839 // Custom array adapter to override text colors
840 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
842 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
846 public View
getView(int position
, View convertView
, ViewGroup parent
) {
847 View v
= super.getView(position
, convertView
, parent
);
849 ((TextView
) v
).setTextColor(getResources().getColorStateList(
850 android
.R
.color
.white
));
852 fixRoot((TextView
) v
);
856 public View
getDropDownView(int position
, View convertView
,
858 View v
= super.getDropDownView(position
, convertView
, parent
);
860 ((TextView
) v
).setTextColor(getResources().getColorStateList(
861 android
.R
.color
.white
));
863 fixRoot((TextView
) v
);
867 private void fixRoot(TextView v
) {
868 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
869 v
.setText(R
.string
.default_display_name_for_root_folder
);
875 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
878 * {@link BroadcastReceiver} to enable syncing feedback in UI
881 public void onReceive(Context context
, Intent intent
) {
883 String event
= intent
.getAction();
884 Log_OC
.d(TAG
, "Received broadcast " + event
);
885 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
886 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
887 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
888 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
892 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
893 mSyncInProgress
= true
;
896 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
897 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
899 if (currentDir
== null
) {
900 // current folder was removed from the server
901 Toast
.makeText( FileDisplayActivity
.this,
902 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
908 if (currentFile
== null
&& !getFile().isFolder()) {
909 // currently selected file was removed in the server, and now we know it
910 cleanSecondFragment();
911 currentFile
= currentDir
;
914 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
915 OCFileListFragment fileListFragment
= getListOfFilesFragment();
916 if (fileListFragment
!= null
) {
917 fileListFragment
.listDirectory(currentDir
);
920 setFile(currentFile
);
923 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
926 removeStickyBroadcast(intent
);
927 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
928 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
931 if (synchResult
!= null
) {
932 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
933 mLastSslUntrustedServerResult
= synchResult
;
936 } catch (RuntimeException e
) {
937 // avoid app crashes after changing the serial id of RemoteOperationResult
938 // in owncloud library with broadcast notifications pending to process
939 removeStickyBroadcast(intent
);
946 * Once the file upload has finished -> update view
948 private class UploadFinishReceiver
extends BroadcastReceiver
{
950 * Once the file upload has finished -> update view
951 * @author David A. Velasco
952 * {@link BroadcastReceiver} to enable upload feedback in UI
955 public void onReceive(Context context
, Intent intent
) {
956 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
957 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
958 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
959 OCFile currentDir
= getCurrentDir();
960 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
961 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
963 if (sameAccount
&& isDescendant
) {
964 refreshListOfFilesFragment();
967 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
968 boolean renamedInUpload
= getFile().getRemotePath().
969 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
970 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
972 FileFragment details
= getSecondFragment();
973 boolean detailFragmentIsShown
= (details
!= null
&&
974 details
instanceof FileDetailFragment
);
976 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
978 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
980 if (renamedInUpload
) {
981 String newName
= (new File(uploadedRemotePath
)).getName();
982 Toast msg
= Toast
.makeText(
985 getString(R
.string
.filedetails_renamed_in_upload_msg
),
990 if (uploadWasFine
|| getFile().fileExists()) {
991 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
993 cleanSecondFragment();
996 // Force the preview if the file is an image
997 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
998 startImagePreview(getFile());
999 } // TODO what about other kind of previews?
1002 removeStickyBroadcast(intent
);
1010 * Class waiting for broadcast events from the {@link FielDownloader} service.
1012 * Updates the UI when a download is started or finished, provided that it is relevant for the
1015 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1017 public void onReceive(Context context
, Intent intent
) {
1018 boolean sameAccount
= isSameAccount(context
, intent
);
1019 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1020 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1022 if (sameAccount
&& isDescendant
) {
1023 refreshListOfFilesFragment();
1024 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1027 if (mWaitingToSend
!= null
) {
1028 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1029 if (mWaitingToSend
.isDown()) {
1030 sendDownloadedFile();
1034 removeStickyBroadcast(intent
);
1037 private boolean isDescendant(String downloadedRemotePath
) {
1038 OCFile currentDir
= getCurrentDir();
1039 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1042 private boolean isSameAccount(Context context
, Intent intent
) {
1043 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1044 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1049 public void browseToRoot() {
1050 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1051 if (listOfFiles
!= null
) { // should never be null, indeed
1052 while (mDirectories
.getCount() > 1) {
1055 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1056 listOfFiles
.listDirectory(root
);
1057 setFile(listOfFiles
.getCurrentFile());
1058 startSyncFolderOperation(root
);
1060 cleanSecondFragment();
1064 public void browseTo(OCFile folder
) {
1065 if (folder
== null
|| !folder
.isFolder()) {
1066 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1068 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1069 if (listOfFiles
!= null
) {
1070 setNavigationListWithFolder(folder
);
1071 listOfFiles
.listDirectory(folder
);
1072 setFile(listOfFiles
.getCurrentFile());
1073 startSyncFolderOperation(folder
);
1075 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1077 cleanSecondFragment();
1084 * Updates action bar and second fragment, if in dual pane mode.
1087 public void onBrowsedDownTo(OCFile directory
) {
1088 pushDirname(directory
);
1089 cleanSecondFragment();
1092 startSyncFolderOperation(directory
);
1097 * Shows the information of the {@link OCFile} received as a
1098 * parameter in the second fragment.
1100 * @param file {@link OCFile} whose details will be shown
1103 public void showDetails(OCFile file
) {
1104 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1105 setSecondFragment(detailFragment
);
1106 updateFragmentsVisibility(true
);
1107 updateNavigationElementsInActionBar(file
);
1115 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1116 ActionBar actionBar
= getSupportActionBar();
1117 if (chosenFile
== null
|| mDualPane
) {
1118 // only list of files - set for browsing through folders
1119 OCFile currentDir
= getCurrentDir();
1120 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1121 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1122 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1124 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1126 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1127 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1130 actionBar
.setDisplayHomeAsUpEnabled(true
);
1131 actionBar
.setDisplayShowTitleEnabled(true
);
1132 actionBar
.setTitle(chosenFile
.getFileName());
1133 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1139 protected ServiceConnection
newTransferenceServiceConnection() {
1140 return new ListServiceConnection();
1143 /** Defines callbacks for service binding, passed to bindService() */
1144 private class ListServiceConnection
implements ServiceConnection
{
1147 public void onServiceConnected(ComponentName component
, IBinder service
) {
1148 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1149 Log_OC
.d(TAG
, "Download service connected");
1150 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1151 if (mWaitingToPreview
!= null
)
1152 if (getStorageManager() != null
) {
1153 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1154 if (!mWaitingToPreview
.isDown()) {
1155 requestForDownload();
1159 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1160 Log_OC
.d(TAG
, "Upload service connected");
1161 mUploaderBinder
= (FileUploaderBinder
) service
;
1165 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1166 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1167 if (listOfFiles
!= null
) {
1168 listOfFiles
.listDirectory();
1170 FileFragment secondFragment
= getSecondFragment();
1171 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1172 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1173 detailFragment
.listenForTransferProgress();
1174 detailFragment
.updateFileDetails(false
, false
);
1179 public void onServiceDisconnected(ComponentName component
) {
1180 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1181 Log_OC
.d(TAG
, "Download service disconnected");
1182 mDownloaderBinder
= null
;
1183 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1184 Log_OC
.d(TAG
, "Upload service disconnected");
1185 mUploaderBinder
= null
;
1193 * Launch an intent to request the PIN code to the user before letting him use the app
1195 private void requestPinCode() {
1196 boolean pinStart
= false
;
1197 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1198 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1200 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1201 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1208 public void onSavedCertificate() {
1209 startSyncFolderOperation(getCurrentDir());
1214 public void onFailedSavingCertificate() {
1215 showDialog(DIALOG_CERT_NOT_SAVED
);
1219 public void onCancelCertificate() {
1224 * Updates the view associated to the activity after the finish of some operation over files
1225 * in the current account.
1227 * @param operation Removal operation performed.
1228 * @param result Result of the removal.
1231 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1232 super.onRemoteOperationFinish(operation
, result
);
1234 if (operation
instanceof RemoveFileOperation
) {
1235 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1237 } else if (operation
instanceof RenameFileOperation
) {
1238 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1240 } else if (operation
instanceof SynchronizeFileOperation
) {
1241 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1243 } else if (operation
instanceof CreateFolderOperation
) {
1244 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1246 } else if (operation
instanceof CreateShareOperation
) {
1247 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1249 } else if (operation
instanceof UnshareLinkOperation
) {
1250 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1257 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1258 if (result
.isSuccess()) {
1259 refreshShowDetails();
1260 refreshListOfFilesFragment();
1265 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1266 if (result
.isSuccess()) {
1267 refreshShowDetails();
1268 refreshListOfFilesFragment();
1270 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1271 cleanSecondFragment();
1272 refreshListOfFilesFragment();
1276 private void refreshShowDetails() {
1277 FileFragment details
= getSecondFragment();
1278 if (details
!= null
) {
1279 OCFile file
= details
.getFile();
1281 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1282 if (details
instanceof PreviewMediaFragment
) {
1283 // Refresh OCFile of the fragment
1284 ((PreviewMediaFragment
) details
).updateFile(file
);
1289 invalidateOptionsMenu();
1294 * Updates the view associated to the activity after the finish of an operation trying to remove a
1297 * @param operation Removal operation performed.
1298 * @param result Result of the removal.
1300 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1301 dismissLoadingDialog();
1302 if (result
.isSuccess()) {
1303 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1305 OCFile removedFile
= operation
.getFile();
1306 FileFragment second
= getSecondFragment();
1307 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1308 if (second
instanceof PreviewMediaFragment
) {
1309 ((PreviewMediaFragment
)second
).stopPreview(true
);
1311 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1312 cleanSecondFragment();
1314 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1315 refreshListOfFilesFragment();
1317 invalidateOptionsMenu();
1319 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1321 if (result
.isSslRecoverableException()) {
1322 mLastSslUntrustedServerResult
= result
;
1323 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1330 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1332 * @param operation Creation operation performed.
1333 * @param result Result of the creation.
1335 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1336 if (result
.isSuccess()) {
1337 dismissLoadingDialog();
1338 refreshListOfFilesFragment();
1340 dismissLoadingDialog();
1341 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1342 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1345 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1348 } catch (NotFoundException e
) {
1349 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1357 * Updates the view associated to the activity after the finish of an operation trying to rename a
1360 * @param operation Renaming operation performed.
1361 * @param result Result of the renaming.
1363 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1364 dismissLoadingDialog();
1365 OCFile renamedFile
= operation
.getFile();
1366 if (result
.isSuccess()) {
1367 FileFragment details
= getSecondFragment();
1368 if (details
!= null
)
1369 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1370 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1371 showDetails(renamedFile
);
1373 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1374 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1375 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1376 int position
= ((PreviewMediaFragment
)details
).getPosition();
1377 startMediaPreview(renamedFile
, position
, true
);
1379 getFileOperationsHelper().openFile(renamedFile
);
1383 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1384 refreshListOfFilesFragment();
1388 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1389 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1391 // TODO throw again the new rename dialog
1392 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1393 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1396 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1398 if (result
.isSslRecoverableException()) {
1399 mLastSslUntrustedServerResult
= result
;
1400 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1406 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1407 dismissLoadingDialog();
1408 OCFile syncedFile
= operation
.getLocalFile();
1409 if (!result
.isSuccess()) {
1410 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1411 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1412 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1413 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1419 if (operation
.transferWasRequested()) {
1420 onTransferStateChanged(syncedFile
, true
, true
);
1423 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1434 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1435 refreshListOfFilesFragment();
1436 FileFragment details
= getSecondFragment();
1437 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1438 if (downloading
|| uploading
) {
1439 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1441 if (!file
.fileExists()) {
1442 cleanSecondFragment();
1444 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1452 private void requestForDownload() {
1453 Account account
= getAccount();
1454 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1455 Intent i
= new Intent(this, FileDownloader
.class);
1456 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1457 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1463 private OCFile
getCurrentDir() {
1464 OCFile file
= getFile();
1466 if (file
.isFolder()) {
1468 } else if (getStorageManager() != null
) {
1469 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1470 return getStorageManager().getFileByPath(parentPath
);
1476 public void startSyncFolderOperation(OCFile folder
) {
1477 long currentSyncTime
= System
.currentTimeMillis();
1479 mSyncInProgress
= true
;
1481 // perform folder synchronization
1482 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1485 getFileOperationsHelper().isSharedSupported(),
1486 getStorageManager(),
1488 getApplicationContext()
1490 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1492 setSupportProgressBarIndeterminateVisibility(true
);
1496 * Show untrusted cert dialog
1498 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1499 // Show a dialog with the certificate info
1500 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1501 FragmentManager fm
= getSupportFragmentManager();
1502 FragmentTransaction ft
= fm
.beginTransaction();
1503 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1506 private void requestForDownload(OCFile file
) {
1507 Account account
= getAccount();
1508 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1509 Intent i
= new Intent(this, FileDownloader
.class);
1510 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1511 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1516 private void sendDownloadedFile(){
1517 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1518 mWaitingToSend
= null
;
1523 * Requests the download of the received {@link OCFile} , updates the UI
1524 * to monitor the download progress and prepares the activity to send the file
1525 * when the download finishes.
1527 * @param file {@link OCFile} to download and preview.
1529 public void startDownloadForSending(OCFile file
) {
1530 mWaitingToSend
= file
;
1531 requestForDownload(mWaitingToSend
);
1532 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1533 updateFragmentsVisibility(hasSecondFragment
);
1537 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1539 * @param file Image {@link OCFile} to show.
1541 public void startImagePreview(OCFile file
) {
1542 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1543 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1544 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1545 startActivity(showDetailsIntent
);
1550 * Stars the preview of an already down media {@link OCFile}.
1552 * @param file Media {@link OCFile} to preview.
1553 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1554 * @param autoplay When 'true', the playback will start without user interactions.
1556 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1557 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1558 setSecondFragment(mediaFragment
);
1559 updateFragmentsVisibility(true
);
1560 updateNavigationElementsInActionBar(file
);
1565 * Requests the download of the received {@link OCFile} , updates the UI
1566 * to monitor the download progress and prepares the activity to preview
1567 * or open the file when the download finishes.
1569 * @param file {@link OCFile} to download and preview.
1571 public void startDownloadForPreview(OCFile file
) {
1572 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1573 setSecondFragment(detailFragment
);
1574 mWaitingToPreview
= file
;
1575 requestForDownload();
1576 updateFragmentsVisibility(true
);
1577 updateNavigationElementsInActionBar(file
);
1582 public void cancelTransference(OCFile file
) {
1583 getFileOperationsHelper().cancelTransference(file
);
1584 if (mWaitingToPreview
!= null
&&
1585 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1586 mWaitingToPreview
= null
;
1588 if (mWaitingToSend
!= null
&&
1589 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1590 mWaitingToSend
= null
;
1592 onTransferStateChanged(file
, false
, false
);