1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 //import android.support.v4.content.LocalBroadcastManager;
52 import android
.util
.Log
;
53 import android
.view
.View
;
54 import android
.view
.ViewGroup
;
55 import android
.widget
.ArrayAdapter
;
56 import android
.widget
.TextView
;
57 import android
.widget
.Toast
;
59 import com
.actionbarsherlock
.app
.ActionBar
;
60 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
61 import com
.actionbarsherlock
.view
.Menu
;
62 import com
.actionbarsherlock
.view
.MenuInflater
;
63 import com
.actionbarsherlock
.view
.MenuItem
;
64 import com
.actionbarsherlock
.view
.Window
;
65 import com
.owncloud
.android
.MainApp
;
66 import com
.owncloud
.android
.R
;
67 import com
.owncloud
.android
.datamodel
.OCFile
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
;
69 import com
.owncloud
.android
.files
.services
.FileObserverService
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
73 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
77 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
78 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RenameFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
87 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
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
) {
166 Intent observer_intent
= new Intent(this, FileObserverService
.class);
167 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
168 startService(observer_intent
);
170 /// Load of saved instance state
171 if(savedInstanceState
!= null
) {
172 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
173 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
174 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
177 mWaitingToPreview
= null
;
178 mSyncInProgress
= false
;
179 mWaitingToSend
= null
;
184 // Inflate and set the layout view
185 setContentView(R
.layout
.files
);
186 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
187 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
188 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
189 if (savedInstanceState
== null
) {
190 createMinFragments();
194 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
195 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
196 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
198 Log_OC
.d(TAG
, "onCreate() end");
202 protected void onStart() {
204 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
208 protected void onDestroy() {
213 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
216 protected void onAccountSet(boolean stateWasRecovered
) {
217 super.onAccountSet(stateWasRecovered
);
218 if (getAccount() != null
) {
219 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
220 OCFile file
= getFile();
221 // get parent from path
222 String parentPath
= "";
224 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
225 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
226 // get parent from path
227 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
228 if (getStorageManager().getFileByPath(parentPath
) == null
)
229 file
= null
; // not able to know the directory where the file is uploading
231 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
235 // fall back to root folder
236 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
239 setNavigationListWithFolder(file
);
241 if (!stateWasRecovered
) {
242 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
243 initFragmentsWithFile();
244 if (file
.isFolder()) {
245 startSyncFolderOperation(file
);
249 updateFragmentsVisibility(!file
.isFolder());
250 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
256 private void setNavigationListWithFolder(OCFile file
) {
257 mDirectories
.clear();
258 OCFile fileIt
= file
;
260 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
261 if (fileIt
.isFolder()) {
262 mDirectories
.add(fileIt
.getFileName());
264 // get parent from path
265 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
266 fileIt
= getStorageManager().getFileByPath(parentPath
);
268 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
272 private void createMinFragments() {
273 OCFileListFragment listOfFiles
= new OCFileListFragment();
274 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
275 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
276 transaction
.commit();
279 private void initFragmentsWithFile() {
280 if (getAccount() != null
&& getFile() != null
) {
282 OCFileListFragment listOfFiles
= getListOfFilesFragment();
283 if (listOfFiles
!= null
) {
284 listOfFiles
.listDirectory(getCurrentDir());
286 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
290 OCFile file
= getFile();
291 Fragment secondFragment
= chooseInitialSecondFragment(file
);
292 if (secondFragment
!= null
) {
293 setSecondFragment(secondFragment
);
294 updateFragmentsVisibility(true
);
295 updateNavigationElementsInActionBar(file
);
298 cleanSecondFragment();
302 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
303 if (getAccount() == null
) {
304 Log
.wtf(TAG
, "\t account is NULL");
306 if (getFile() == null
) {
307 Log
.wtf(TAG
, "\t file is NULL");
312 private Fragment
chooseInitialSecondFragment(OCFile file
) {
313 Fragment secondFragment
= null
;
314 if (file
!= null
&& !file
.isFolder()) {
315 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
316 && file
.getLastSyncDateForProperties() > 0 // temporal fix
318 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
319 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
320 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
323 secondFragment
= new FileDetailFragment(file
, getAccount());
326 return secondFragment
;
331 * Replaces the second fragment managed by the activity with the received as
334 * Assumes never will be more than two fragments managed at the same time.
336 * @param fragment New second Fragment to set.
338 private void setSecondFragment(Fragment fragment
) {
339 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
340 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
341 transaction
.commit();
345 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
347 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
348 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
350 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
351 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
354 } else if (existsSecondFragment
) {
355 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
356 mLeftFragmentContainer
.setVisibility(View
.GONE
);
358 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
359 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
363 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
366 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
367 mRightFragmentContainer
.setVisibility(View
.GONE
);
373 private OCFileListFragment
getListOfFilesFragment() {
374 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
375 if (listOfFiles
!= null
) {
376 return (OCFileListFragment
)listOfFiles
;
378 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
382 public FileFragment
getSecondFragment() {
383 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
384 if (second
!= null
) {
385 return (FileFragment
)second
;
390 protected void cleanSecondFragment() {
391 Fragment second
= getSecondFragment();
392 if (second
!= null
) {
393 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
397 updateFragmentsVisibility(false
);
398 updateNavigationElementsInActionBar(null
);
401 protected void refreshListOfFilesFragment() {
402 OCFileListFragment fileListFragment
= getListOfFilesFragment();
403 if (fileListFragment
!= null
) {
404 fileListFragment
.listDirectory();
408 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
409 FileFragment secondFragment
= getSecondFragment();
410 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
411 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
412 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
413 OCFile fileInFragment
= detailsFragment
.getFile();
414 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
415 // the user browsed to other file ; forget the automatic preview
416 mWaitingToPreview
= null
;
418 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
419 // grant that the right panel updates the progress bar
420 detailsFragment
.listenForTransferProgress();
421 detailsFragment
.updateFileDetails(true
, false
);
423 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
424 // update the right panel
425 boolean detailsFragmentChanged
= false
;
428 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
429 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
430 startMediaPreview(mWaitingToPreview
, 0, true
);
431 detailsFragmentChanged
= true
;
433 getFileOperationsHelper().openFile(mWaitingToPreview
);
436 mWaitingToPreview
= null
;
438 if (!detailsFragmentChanged
) {
439 detailsFragment
.updateFileDetails(false
, (success
));
446 public boolean onCreateOptionsMenu(Menu menu
) {
447 MenuInflater inflater
= getSherlock().getMenuInflater();
448 inflater
.inflate(R
.menu
.main_menu
, menu
);
453 public boolean onOptionsItemSelected(MenuItem item
) {
454 boolean retval
= true
;
455 switch (item
.getItemId()) {
456 case R
.id
.action_create_dir
: {
457 CreateFolderDialogFragment dialog
=
458 CreateFolderDialogFragment
.newInstance(getCurrentDir());
459 dialog
.show(getSupportFragmentManager(), "createdirdialog");
462 case R
.id
.action_sync_account
: {
463 startSynchronization();
466 case R
.id
.action_upload
: {
467 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
470 case R
.id
.action_settings
: {
471 Intent settingsIntent
= new Intent(this, Preferences
.class);
472 startActivity(settingsIntent
);
475 case android
.R
.id
.home
: {
476 FileFragment second
= getSecondFragment();
477 OCFile currentDir
= getCurrentDir();
478 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
479 (second
!= null
&& second
.getFile() != null
)) {
486 retval
= super.onOptionsItemSelected(item
);
491 private void startSynchronization() {
492 Log_OC
.e(TAG
, "Got to start sync");
493 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
494 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
495 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
496 Bundle bundle
= new Bundle();
497 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
498 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
499 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
500 ContentResolver
.requestSync(
502 MainApp
.getAuthority(), bundle
);
504 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
505 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
506 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
507 builder
.setExpedited(true
);
508 builder
.setManual(true
);
510 SyncRequest request
= builder
.build();
511 ContentResolver
.requestSync(request
);
517 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
518 if (itemPosition
!= 0) {
519 String targetPath
= "";
520 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
521 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
523 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
524 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
525 if (targetFolder
!= null
) {
526 browseTo(targetFolder
);
529 // the next operation triggers a new call to this method, but it's necessary to
530 // ensure that the name exposed in the action bar is the current directory when the
531 // user selected it in the navigation list
532 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
533 getSupportActionBar().setSelectedNavigationItem(0);
539 * Called, when the user selected something for uploading
541 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
542 super.onActivityResult(requestCode
, resultCode
, data
);
544 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
545 requestSimpleUpload(data
, resultCode
);
547 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
548 requestMultipleUpload(data
, resultCode
);
553 private void requestMultipleUpload(Intent data
, int resultCode
) {
554 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
555 if (filePaths
!= null
) {
556 String
[] remotePaths
= new String
[filePaths
.length
];
557 String remotePathBase
= "";
558 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
559 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
561 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
562 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
563 for (int j
= 0; j
< remotePaths
.length
; j
++) {
564 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
567 Intent i
= new Intent(this, FileUploader
.class);
568 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
569 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
570 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
571 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
572 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
573 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
577 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
578 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
585 private void requestSimpleUpload(Intent data
, int resultCode
) {
586 String filepath
= null
;
588 Uri selectedImageUri
= data
.getData();
590 String filemanagerstring
= selectedImageUri
.getPath();
591 String selectedImagePath
= getPath(selectedImageUri
);
593 if (selectedImagePath
!= null
)
594 filepath
= selectedImagePath
;
596 filepath
= filemanagerstring
;
598 } catch (Exception e
) {
599 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
603 if (filepath
== null
) {
604 Log_OC
.e(TAG
, "Couldnt resolve path to file");
605 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
611 Intent i
= new Intent(this, FileUploader
.class);
612 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
614 String remotepath
= new String();
615 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
616 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
618 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
619 remotepath
+= OCFile
.PATH_SEPARATOR
;
620 remotepath
+= new File(filepath
).getName();
622 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
623 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
624 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
625 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
626 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
631 public void onBackPressed() {
632 OCFileListFragment listOfFiles
= getListOfFilesFragment();
633 if (mDualPane
|| getSecondFragment() == null
) {
634 if (listOfFiles
!= null
) { // should never be null, indeed
635 if (mDirectories
.getCount() <= 1) {
639 int levelsUp
= listOfFiles
.onBrowseUp();
640 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
645 if (listOfFiles
!= null
) { // should never be null, indeed
646 setFile(listOfFiles
.getCurrentFile());
648 cleanSecondFragment();
653 protected void onSaveInstanceState(Bundle outState
) {
654 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
655 Log_OC
.e(TAG
, "onSaveInstanceState() start");
656 super.onSaveInstanceState(outState
);
657 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
658 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
659 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
660 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
662 Log_OC
.d(TAG
, "onSaveInstanceState() end");
668 protected void onResume() {
670 Log_OC
.e(TAG
, "onResume() start");
672 // refresh list of files
673 refreshListOfFilesFragment();
675 // Listen for sync messages
676 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
677 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
678 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
679 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
680 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
681 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
682 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
683 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
685 // Listen for upload messages
686 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
687 mUploadFinishReceiver
= new UploadFinishReceiver();
688 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
690 // Listen for download messages
691 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
692 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
693 mDownloadFinishReceiver
= new DownloadFinishReceiver();
694 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
696 Log_OC
.d(TAG
, "onResume() end");
701 protected void onPause() {
702 Log_OC
.e(TAG
, "onPause() start");
703 if (mSyncBroadcastReceiver
!= null
) {
704 unregisterReceiver(mSyncBroadcastReceiver
);
705 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
706 mSyncBroadcastReceiver
= null
;
708 if (mUploadFinishReceiver
!= null
) {
709 unregisterReceiver(mUploadFinishReceiver
);
710 mUploadFinishReceiver
= null
;
712 if (mDownloadFinishReceiver
!= null
) {
713 unregisterReceiver(mDownloadFinishReceiver
);
714 mDownloadFinishReceiver
= null
;
718 Log_OC
.d(TAG
, "onPause() end");
724 protected Dialog
onCreateDialog(int id
) {
725 Dialog dialog
= null
;
726 AlertDialog
.Builder builder
;
728 case DIALOG_SHORT_WAIT
: {
729 ProgressDialog working_dialog
= new ProgressDialog(this);
730 working_dialog
.setMessage(getResources().getString(
731 R
.string
.wait_a_moment
));
732 working_dialog
.setIndeterminate(true
);
733 working_dialog
.setCancelable(false
);
734 dialog
= working_dialog
;
737 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
739 String
[] items
= null
;
741 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
742 getString(R
.string
.actionbar_upload_from_apps
),
743 getString(R
.string
.actionbar_failed_instant_upload
) };
745 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
746 getString(R
.string
.actionbar_upload_from_apps
) };
748 if (InstantUploadActivity
.IS_ENABLED
)
753 builder
= new AlertDialog
.Builder(this);
754 builder
.setTitle(R
.string
.actionbar_upload
);
755 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
756 public void onClick(DialogInterface dialog
, int item
) {
759 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
760 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
761 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
763 // TODO create and handle new fragment
764 // LocalFileListFragment
766 } else if (item
== 1) {
767 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
768 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
769 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
770 ACTION_SELECT_CONTENT_FROM_APPS
);
771 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
772 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
773 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
774 startActivity(action
);
778 dialog
= builder
.create();
781 case DIALOG_CERT_NOT_SAVED
: {
782 builder
= new AlertDialog
.Builder(this);
783 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
784 builder
.setCancelable(false
);
785 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
787 public void onClick(DialogInterface dialog
, int which
) {
791 dialog
= builder
.create();
803 * Translates a content URI of an image to a physical path
805 * @param uri The URI to resolve
806 * @return The path to the image or null if it could not be found
808 public String
getPath(Uri uri
) {
809 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
810 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
811 if (cursor
!= null
) {
812 int column_index
= cursor
813 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
814 cursor
.moveToFirst();
815 return cursor
.getString(column_index
);
821 * Pushes a directory to the drop down list
822 * @param directory to push
823 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
825 public void pushDirname(OCFile directory
) {
826 if(!directory
.isFolder()){
827 throw new IllegalArgumentException("Only directories may be pushed!");
829 mDirectories
.insert(directory
.getFileName(), 0);
834 * Pops a directory name from the drop down list
835 * @return True, unless the stack is empty
837 public boolean popDirname() {
838 mDirectories
.remove(mDirectories
.getItem(0));
839 return !mDirectories
.isEmpty();
842 // Custom array adapter to override text colors
843 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
845 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
849 public View
getView(int position
, View convertView
, ViewGroup parent
) {
850 View v
= super.getView(position
, convertView
, parent
);
852 ((TextView
) v
).setTextColor(getResources().getColorStateList(
853 android
.R
.color
.white
));
855 fixRoot((TextView
) v
);
859 public View
getDropDownView(int position
, View convertView
,
861 View v
= super.getDropDownView(position
, convertView
, parent
);
863 ((TextView
) v
).setTextColor(getResources().getColorStateList(
864 android
.R
.color
.white
));
866 fixRoot((TextView
) v
);
870 private void fixRoot(TextView v
) {
871 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
872 v
.setText(R
.string
.default_display_name_for_root_folder
);
878 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
881 * {@link BroadcastReceiver} to enable syncing feedback in UI
884 public void onReceive(Context context
, Intent intent
) {
886 String event
= intent
.getAction();
887 Log_OC
.d(TAG
, "Received broadcast " + event
);
888 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
889 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
890 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
891 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
895 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
896 mSyncInProgress
= true
;
899 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
900 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
902 if (currentDir
== null
) {
903 // current folder was removed from the server
904 Toast
.makeText( FileDisplayActivity
.this,
905 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
911 if (currentFile
== null
&& !getFile().isFolder()) {
912 // currently selected file was removed in the server, and now we know it
913 cleanSecondFragment();
914 currentFile
= currentDir
;
917 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
918 OCFileListFragment fileListFragment
= getListOfFilesFragment();
919 if (fileListFragment
!= null
) {
920 fileListFragment
.listDirectory(currentDir
);
923 setFile(currentFile
);
926 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
928 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
930 /// TODO refactor and make common
931 synchResult
!= null
&& !synchResult
.isSuccess() &&
932 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
933 synchResult
.isIdPRedirection() ||
934 (synchResult
.isException() && synchResult
.getException()
935 instanceof AuthenticatorException
))) {
937 OwnCloudClient client
= null
;
939 client
= ((MainApp
)getApplicationContext()).
940 getOwnCloudClientManager().removeClientFor(
943 // TODO get rid of these exceptions
944 } catch (AccountNotFoundException e
) {
946 } catch (AuthenticatorException e
) {
948 } catch (OperationCanceledException e
) {
950 } catch (IOException e
) {
954 if (client
!= null
) {
955 OwnCloudCredentials cred
= client
.getCredentials();
957 AccountManager am
= AccountManager
.get(context
);
958 if (cred
.authTokenExpires()) {
959 am
.invalidateAuthToken(
964 am
.clearPassword(getAccount());
969 requestCredentialsUpdate();
973 removeStickyBroadcast(intent
);
974 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
975 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
979 if (synchResult
!= null
) {
980 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
981 mLastSslUntrustedServerResult
= synchResult
;
984 } catch (RuntimeException e
) {
985 // avoid app crashes after changing the serial id of RemoteOperationResult
986 // in owncloud library with broadcast notifications pending to process
987 removeStickyBroadcast(intent
);
994 * Once the file upload has finished -> update view
996 private class UploadFinishReceiver
extends BroadcastReceiver
{
998 * Once the file upload has finished -> update view
999 * @author David A. Velasco
1000 * {@link BroadcastReceiver} to enable upload feedback in UI
1003 public void onReceive(Context context
, Intent intent
) {
1004 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1005 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1006 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1007 OCFile currentDir
= getCurrentDir();
1008 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1009 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1011 if (sameAccount
&& isDescendant
) {
1012 refreshListOfFilesFragment();
1015 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1016 boolean renamedInUpload
= getFile().getRemotePath().
1017 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1018 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1020 FileFragment details
= getSecondFragment();
1021 boolean detailFragmentIsShown
= (details
!= null
&&
1022 details
instanceof FileDetailFragment
);
1024 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1025 if (uploadWasFine
) {
1026 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1028 if (renamedInUpload
) {
1029 String newName
= (new File(uploadedRemotePath
)).getName();
1030 Toast msg
= Toast
.makeText(
1033 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1038 if (uploadWasFine
|| getFile().fileExists()) {
1039 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1041 cleanSecondFragment();
1044 // Force the preview if the file is an image
1045 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1046 startImagePreview(getFile());
1047 } // TODO what about other kind of previews?
1050 removeStickyBroadcast(intent
);
1058 * Class waiting for broadcast events from the {@link FielDownloader} service.
1060 * Updates the UI when a download is started or finished, provided that it is relevant for the
1063 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1065 public void onReceive(Context context
, Intent intent
) {
1066 boolean sameAccount
= isSameAccount(context
, intent
);
1067 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1068 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1070 if (sameAccount
&& isDescendant
) {
1071 refreshListOfFilesFragment();
1072 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1075 if (mWaitingToSend
!= null
) {
1076 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1077 if (mWaitingToSend
.isDown()) {
1078 sendDownloadedFile();
1082 removeStickyBroadcast(intent
);
1085 private boolean isDescendant(String downloadedRemotePath
) {
1086 OCFile currentDir
= getCurrentDir();
1087 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1090 private boolean isSameAccount(Context context
, Intent intent
) {
1091 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1092 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1097 public void browseToRoot() {
1098 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1099 if (listOfFiles
!= null
) { // should never be null, indeed
1100 while (mDirectories
.getCount() > 1) {
1103 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1104 listOfFiles
.listDirectory(root
);
1105 setFile(listOfFiles
.getCurrentFile());
1106 startSyncFolderOperation(root
);
1108 cleanSecondFragment();
1112 public void browseTo(OCFile folder
) {
1113 if (folder
== null
|| !folder
.isFolder()) {
1114 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1116 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1117 if (listOfFiles
!= null
) {
1118 setNavigationListWithFolder(folder
);
1119 listOfFiles
.listDirectory(folder
);
1120 setFile(listOfFiles
.getCurrentFile());
1121 startSyncFolderOperation(folder
);
1123 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1125 cleanSecondFragment();
1132 * Updates action bar and second fragment, if in dual pane mode.
1135 public void onBrowsedDownTo(OCFile directory
) {
1136 pushDirname(directory
);
1137 cleanSecondFragment();
1140 startSyncFolderOperation(directory
);
1145 * Shows the information of the {@link OCFile} received as a
1146 * parameter in the second fragment.
1148 * @param file {@link OCFile} whose details will be shown
1151 public void showDetails(OCFile file
) {
1152 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1153 setSecondFragment(detailFragment
);
1154 updateFragmentsVisibility(true
);
1155 updateNavigationElementsInActionBar(file
);
1163 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1164 ActionBar actionBar
= getSupportActionBar();
1165 if (chosenFile
== null
|| mDualPane
) {
1166 // only list of files - set for browsing through folders
1167 OCFile currentDir
= getCurrentDir();
1168 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1169 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1170 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1172 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1174 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1175 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1178 actionBar
.setDisplayHomeAsUpEnabled(true
);
1179 actionBar
.setDisplayShowTitleEnabled(true
);
1180 actionBar
.setTitle(chosenFile
.getFileName());
1181 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1187 protected ServiceConnection
newTransferenceServiceConnection() {
1188 return new ListServiceConnection();
1191 /** Defines callbacks for service binding, passed to bindService() */
1192 private class ListServiceConnection
implements ServiceConnection
{
1195 public void onServiceConnected(ComponentName component
, IBinder service
) {
1196 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1197 Log_OC
.d(TAG
, "Download service connected");
1198 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1199 if (mWaitingToPreview
!= null
)
1200 if (getStorageManager() != null
) {
1201 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1202 if (!mWaitingToPreview
.isDown()) {
1203 requestForDownload();
1207 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1208 Log_OC
.d(TAG
, "Upload service connected");
1209 mUploaderBinder
= (FileUploaderBinder
) service
;
1213 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1214 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1215 if (listOfFiles
!= null
) {
1216 listOfFiles
.listDirectory();
1218 FileFragment secondFragment
= getSecondFragment();
1219 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1220 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1221 detailFragment
.listenForTransferProgress();
1222 detailFragment
.updateFileDetails(false
, false
);
1227 public void onServiceDisconnected(ComponentName component
) {
1228 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1229 Log_OC
.d(TAG
, "Download service disconnected");
1230 mDownloaderBinder
= null
;
1231 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1232 Log_OC
.d(TAG
, "Upload service disconnected");
1233 mUploaderBinder
= null
;
1241 * Launch an intent to request the PIN code to the user before letting him use the app
1243 private void requestPinCode() {
1244 boolean pinStart
= false
;
1245 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1246 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1248 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1249 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1256 public void onSavedCertificate() {
1257 startSyncFolderOperation(getCurrentDir());
1262 public void onFailedSavingCertificate() {
1263 showDialog(DIALOG_CERT_NOT_SAVED
);
1267 public void onCancelCertificate() {
1272 * Updates the view associated to the activity after the finish of some operation over files
1273 * in the current account.
1275 * @param operation Removal operation performed.
1276 * @param result Result of the removal.
1279 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1280 super.onRemoteOperationFinish(operation
, result
);
1282 if (operation
instanceof RemoveFileOperation
) {
1283 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1285 } else if (operation
instanceof RenameFileOperation
) {
1286 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1288 } else if (operation
instanceof SynchronizeFileOperation
) {
1289 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1291 } else if (operation
instanceof CreateFolderOperation
) {
1292 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1294 } else if (operation
instanceof CreateShareOperation
) {
1295 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1297 } else if (operation
instanceof UnshareLinkOperation
) {
1298 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1305 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1306 if (result
.isSuccess()) {
1307 refreshShowDetails();
1308 refreshListOfFilesFragment();
1313 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1314 if (result
.isSuccess()) {
1315 refreshShowDetails();
1316 refreshListOfFilesFragment();
1318 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1319 cleanSecondFragment();
1320 refreshListOfFilesFragment();
1324 private void refreshShowDetails() {
1325 FileFragment details
= getSecondFragment();
1326 if (details
!= null
) {
1327 OCFile file
= details
.getFile();
1329 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1330 if (details
instanceof PreviewMediaFragment
) {
1331 // Refresh OCFile of the fragment
1332 ((PreviewMediaFragment
) details
).updateFile(file
);
1337 invalidateOptionsMenu();
1342 * Updates the view associated to the activity after the finish of an operation trying to remove a
1345 * @param operation Removal operation performed.
1346 * @param result Result of the removal.
1348 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1349 dismissLoadingDialog();
1351 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1355 if (result
.isSuccess()) {
1356 OCFile removedFile
= operation
.getFile();
1357 FileFragment second
= getSecondFragment();
1358 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1359 if (second
instanceof PreviewMediaFragment
) {
1360 ((PreviewMediaFragment
)second
).stopPreview(true
);
1362 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1363 cleanSecondFragment();
1365 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1366 refreshListOfFilesFragment();
1368 invalidateOptionsMenu();
1370 if (result
.isSslRecoverableException()) {
1371 mLastSslUntrustedServerResult
= result
;
1372 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1379 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1381 * @param operation Creation operation performed.
1382 * @param result Result of the creation.
1384 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1385 if (result
.isSuccess()) {
1386 dismissLoadingDialog();
1387 refreshListOfFilesFragment();
1389 dismissLoadingDialog();
1391 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1392 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1396 } catch (NotFoundException e
) {
1397 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1404 * Updates the view associated to the activity after the finish of an operation trying to rename a
1407 * @param operation Renaming operation performed.
1408 * @param result Result of the renaming.
1410 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1411 dismissLoadingDialog();
1412 OCFile renamedFile
= operation
.getFile();
1413 if (result
.isSuccess()) {
1414 FileFragment details
= getSecondFragment();
1415 if (details
!= null
) {
1416 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1417 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1418 showDetails(renamedFile
);
1420 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1421 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1422 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1423 int position
= ((PreviewMediaFragment
)details
).getPosition();
1424 startMediaPreview(renamedFile
, position
, true
);
1426 getFileOperationsHelper().openFile(renamedFile
);
1431 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1432 refreshListOfFilesFragment();
1436 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1440 if (result
.isSslRecoverableException()) {
1441 mLastSslUntrustedServerResult
= result
;
1442 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1447 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1448 dismissLoadingDialog();
1449 OCFile syncedFile
= operation
.getLocalFile();
1450 if (!result
.isSuccess()) {
1451 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1452 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1453 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1454 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1460 if (operation
.transferWasRequested()) {
1461 onTransferStateChanged(syncedFile
, true
, true
);
1464 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1476 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1477 refreshListOfFilesFragment();
1478 FileFragment details
= getSecondFragment();
1479 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1480 if (downloading
|| uploading
) {
1481 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1483 if (!file
.fileExists()) {
1484 cleanSecondFragment();
1486 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1494 private void requestForDownload() {
1495 Account account
= getAccount();
1496 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1497 Intent i
= new Intent(this, FileDownloader
.class);
1498 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1499 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1505 private OCFile
getCurrentDir() {
1506 OCFile file
= getFile();
1508 if (file
.isFolder()) {
1510 } else if (getStorageManager() != null
) {
1511 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1512 return getStorageManager().getFileByPath(parentPath
);
1518 public void startSyncFolderOperation(OCFile folder
) {
1519 long currentSyncTime
= System
.currentTimeMillis();
1521 mSyncInProgress
= true
;
1523 // perform folder synchronization
1524 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1527 getFileOperationsHelper().isSharedSupported(),
1528 getStorageManager(),
1530 getApplicationContext()
1532 synchFolderOp
.execute(getAccount(), this, null
, null
);
1534 setSupportProgressBarIndeterminateVisibility(true
);
1538 * Show untrusted cert dialog
1540 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1541 // Show a dialog with the certificate info
1542 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1543 FragmentManager fm
= getSupportFragmentManager();
1544 FragmentTransaction ft
= fm
.beginTransaction();
1545 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1548 private void requestForDownload(OCFile file
) {
1549 Account account
= getAccount();
1550 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1551 Intent i
= new Intent(this, FileDownloader
.class);
1552 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1553 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1558 private void sendDownloadedFile(){
1559 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1560 mWaitingToSend
= null
;
1565 * Requests the download of the received {@link OCFile} , updates the UI
1566 * to monitor the download progress and prepares the activity to send the file
1567 * when the download finishes.
1569 * @param file {@link OCFile} to download and preview.
1571 public void startDownloadForSending(OCFile file
) {
1572 mWaitingToSend
= file
;
1573 requestForDownload(mWaitingToSend
);
1574 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1575 updateFragmentsVisibility(hasSecondFragment
);
1579 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1581 * @param file Image {@link OCFile} to show.
1583 public void startImagePreview(OCFile file
) {
1584 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1585 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1586 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1587 startActivity(showDetailsIntent
);
1592 * Stars the preview of an already down media {@link OCFile}.
1594 * @param file Media {@link OCFile} to preview.
1595 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1596 * @param autoplay When 'true', the playback will start without user interactions.
1598 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1599 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1600 setSecondFragment(mediaFragment
);
1601 updateFragmentsVisibility(true
);
1602 updateNavigationElementsInActionBar(file
);
1607 * Requests the download of the received {@link OCFile} , updates the UI
1608 * to monitor the download progress and prepares the activity to preview
1609 * or open the file when the download finishes.
1611 * @param file {@link OCFile} to download and preview.
1613 public void startDownloadForPreview(OCFile file
) {
1614 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1615 setSecondFragment(detailFragment
);
1616 mWaitingToPreview
= file
;
1617 requestForDownload();
1618 updateFragmentsVisibility(true
);
1619 updateNavigationElementsInActionBar(file
);
1624 public void cancelTransference(OCFile file
) {
1625 getFileOperationsHelper().cancelTransference(file
);
1626 if (mWaitingToPreview
!= null
&&
1627 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1628 mWaitingToPreview
= null
;
1630 if (mWaitingToSend
!= null
&&
1631 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1632 mWaitingToSend
= null
;
1634 onTransferStateChanged(file
, false
, false
);