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
.OwnCloudClientManagerFactory
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
78 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
79 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.operations
.CreateShareOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
90 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
93 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
100 import com
.owncloud
.android
.utils
.DisplayUtils
;
101 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
102 import com
.owncloud
.android
.utils
.Log_OC
;
106 * Displays, what files the user has available in his ownCloud.
108 * @author Bartek Przybylski
109 * @author David A. Velasco
112 public class FileDisplayActivity
extends HookActivity
implements
113 FileFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
{
115 private ArrayAdapter
<String
> mDirectories
;
117 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
118 private UploadFinishReceiver mUploadFinishReceiver
;
119 private DownloadFinishReceiver mDownloadFinishReceiver
;
120 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
122 private boolean mDualPane
;
123 private View mLeftFragmentContainer
;
124 private View mRightFragmentContainer
;
126 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
127 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
128 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
130 public static final int DIALOG_SHORT_WAIT
= 0;
131 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
132 private static final int DIALOG_CERT_NOT_SAVED
= 2;
134 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
136 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
137 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
141 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
142 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
144 private OCFile mWaitingToPreview
;
146 private boolean mSyncInProgress
= false
;
148 private String DIALOG_UNTRUSTED_CERT
;
150 private OCFile mWaitingToSend
;
153 protected void onCreate(Bundle savedInstanceState
) {
154 Log_OC
.d(TAG
, "onCreate() start");
155 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
157 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
159 // PIN CODE request ; best location is to decide, let's try this first
160 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
162 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
167 Intent observer_intent
= new Intent(this, FileObserverService
.class);
168 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
169 startService(observer_intent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
174 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
175 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
178 mWaitingToPreview
= null
;
179 mSyncInProgress
= false
;
180 mWaitingToSend
= null
;
185 // Inflate and set the layout view
186 setContentView(R
.layout
.files
);
187 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
188 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
189 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
190 if (savedInstanceState
== null
) {
191 createMinFragments();
195 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
196 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
197 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
199 Log_OC
.d(TAG
, "onCreate() end");
203 protected void onStart() {
205 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
209 protected void onDestroy() {
214 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
217 protected void onAccountSet(boolean stateWasRecovered
) {
218 super.onAccountSet(stateWasRecovered
);
219 if (getAccount() != null
) {
220 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
221 OCFile file
= getFile();
222 // get parent from path
223 String parentPath
= "";
225 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
226 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
227 // get parent from path
228 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
229 if (getStorageManager().getFileByPath(parentPath
) == null
)
230 file
= null
; // not able to know the directory where the file is uploading
232 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
236 // fall back to root folder
237 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
240 setNavigationListWithFolder(file
);
242 if (!stateWasRecovered
) {
243 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
244 initFragmentsWithFile();
245 if (file
.isFolder()) {
246 startSyncFolderOperation(file
);
250 updateFragmentsVisibility(!file
.isFolder());
251 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
257 private void setNavigationListWithFolder(OCFile file
) {
258 mDirectories
.clear();
259 OCFile fileIt
= file
;
261 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
262 if (fileIt
.isFolder()) {
263 mDirectories
.add(fileIt
.getFileName());
265 // get parent from path
266 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
267 fileIt
= getStorageManager().getFileByPath(parentPath
);
269 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
273 private void createMinFragments() {
274 OCFileListFragment listOfFiles
= new OCFileListFragment();
275 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
276 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
277 transaction
.commit();
280 private void initFragmentsWithFile() {
281 if (getAccount() != null
&& getFile() != null
) {
283 OCFileListFragment listOfFiles
= getListOfFilesFragment();
284 if (listOfFiles
!= null
) {
285 listOfFiles
.listDirectory(getCurrentDir());
287 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
291 OCFile file
= getFile();
292 Fragment secondFragment
= chooseInitialSecondFragment(file
);
293 if (secondFragment
!= null
) {
294 setSecondFragment(secondFragment
);
295 updateFragmentsVisibility(true
);
296 updateNavigationElementsInActionBar(file
);
299 cleanSecondFragment();
303 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
304 if (getAccount() == null
) {
305 Log
.wtf(TAG
, "\t account is NULL");
307 if (getFile() == null
) {
308 Log
.wtf(TAG
, "\t file is NULL");
313 private Fragment
chooseInitialSecondFragment(OCFile file
) {
314 Fragment secondFragment
= null
;
315 if (file
!= null
&& !file
.isFolder()) {
316 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
317 && file
.getLastSyncDateForProperties() > 0 // temporal fix
319 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
320 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
321 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
324 secondFragment
= new FileDetailFragment(file
, getAccount());
327 return secondFragment
;
332 * Replaces the second fragment managed by the activity with the received as
335 * Assumes never will be more than two fragments managed at the same time.
337 * @param fragment New second Fragment to set.
339 private void setSecondFragment(Fragment fragment
) {
340 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
341 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
342 transaction
.commit();
346 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
348 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
349 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
351 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
352 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
355 } else if (existsSecondFragment
) {
356 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
357 mLeftFragmentContainer
.setVisibility(View
.GONE
);
359 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
360 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
364 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
368 mRightFragmentContainer
.setVisibility(View
.GONE
);
374 private OCFileListFragment
getListOfFilesFragment() {
375 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
376 if (listOfFiles
!= null
) {
377 return (OCFileListFragment
)listOfFiles
;
379 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
383 public FileFragment
getSecondFragment() {
384 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
385 if (second
!= null
) {
386 return (FileFragment
)second
;
391 protected void cleanSecondFragment() {
392 Fragment second
= getSecondFragment();
393 if (second
!= null
) {
394 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
398 updateFragmentsVisibility(false
);
399 updateNavigationElementsInActionBar(null
);
402 protected void refreshListOfFilesFragment() {
403 OCFileListFragment fileListFragment
= getListOfFilesFragment();
404 if (fileListFragment
!= null
) {
405 fileListFragment
.listDirectory();
409 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
410 FileFragment secondFragment
= getSecondFragment();
411 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
412 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
413 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
414 OCFile fileInFragment
= detailsFragment
.getFile();
415 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
416 // the user browsed to other file ; forget the automatic preview
417 mWaitingToPreview
= null
;
419 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
420 // grant that the right panel updates the progress bar
421 detailsFragment
.listenForTransferProgress();
422 detailsFragment
.updateFileDetails(true
, false
);
424 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
425 // update the right panel
426 boolean detailsFragmentChanged
= false
;
429 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
430 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
431 startMediaPreview(mWaitingToPreview
, 0, true
);
432 detailsFragmentChanged
= true
;
434 getFileOperationsHelper().openFile(mWaitingToPreview
);
437 mWaitingToPreview
= null
;
439 if (!detailsFragmentChanged
) {
440 detailsFragment
.updateFileDetails(false
, (success
));
447 public boolean onCreateOptionsMenu(Menu menu
) {
448 MenuInflater inflater
= getSherlock().getMenuInflater();
449 inflater
.inflate(R
.menu
.main_menu
, menu
);
454 public boolean onOptionsItemSelected(MenuItem item
) {
455 boolean retval
= true
;
456 switch (item
.getItemId()) {
457 case R
.id
.action_create_dir
: {
458 CreateFolderDialogFragment dialog
=
459 CreateFolderDialogFragment
.newInstance(getCurrentDir());
460 dialog
.show(getSupportFragmentManager(), "createdirdialog");
463 case R
.id
.action_sync_account
: {
464 startSynchronization();
467 case R
.id
.action_upload
: {
468 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
471 case R
.id
.action_settings
: {
472 Intent settingsIntent
= new Intent(this, Preferences
.class);
473 startActivity(settingsIntent
);
476 case android
.R
.id
.home
: {
477 FileFragment second
= getSecondFragment();
478 OCFile currentDir
= getCurrentDir();
479 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
480 (second
!= null
&& second
.getFile() != null
)) {
487 retval
= super.onOptionsItemSelected(item
);
492 private void startSynchronization() {
493 Log_OC
.e(TAG
, "Got to start sync");
494 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
495 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
496 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
497 Bundle bundle
= new Bundle();
498 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
499 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
500 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
501 ContentResolver
.requestSync(
503 MainApp
.getAuthority(), bundle
);
505 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
506 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
507 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
508 builder
.setExpedited(true
);
509 builder
.setManual(true
);
511 SyncRequest request
= builder
.build();
512 ContentResolver
.requestSync(request
);
518 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
519 if (itemPosition
!= 0) {
520 String targetPath
= "";
521 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
522 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
524 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
525 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
526 if (targetFolder
!= null
) {
527 browseTo(targetFolder
);
530 // the next operation triggers a new call to this method, but it's necessary to
531 // ensure that the name exposed in the action bar is the current directory when the
532 // user selected it in the navigation list
533 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
534 getSupportActionBar().setSelectedNavigationItem(0);
540 * Called, when the user selected something for uploading
542 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
543 super.onActivityResult(requestCode
, resultCode
, data
);
545 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
546 requestSimpleUpload(data
, resultCode
);
548 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
549 requestMultipleUpload(data
, resultCode
);
554 private void requestMultipleUpload(Intent data
, int resultCode
) {
555 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
556 if (filePaths
!= null
) {
557 String
[] remotePaths
= new String
[filePaths
.length
];
558 String remotePathBase
= "";
559 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
560 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
562 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
563 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
564 for (int j
= 0; j
< remotePaths
.length
; j
++) {
565 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
568 Intent i
= new Intent(this, FileUploader
.class);
569 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
570 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
571 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
572 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
573 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
574 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
578 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
579 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
586 private void requestSimpleUpload(Intent data
, int resultCode
) {
587 String filepath
= null
;
589 Uri selectedImageUri
= data
.getData();
591 String filemanagerstring
= selectedImageUri
.getPath();
592 String selectedImagePath
= getPath(selectedImageUri
);
594 if (selectedImagePath
!= null
)
595 filepath
= selectedImagePath
;
597 filepath
= filemanagerstring
;
599 } catch (Exception e
) {
600 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
604 if (filepath
== null
) {
605 Log_OC
.e(TAG
, "Couldnt resolve path to file");
606 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
612 Intent i
= new Intent(this, FileUploader
.class);
613 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
615 String remotepath
= new String();
616 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
617 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
619 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
620 remotepath
+= OCFile
.PATH_SEPARATOR
;
621 remotepath
+= new File(filepath
).getName();
623 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
624 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
625 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
626 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
627 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
632 public void onBackPressed() {
633 OCFileListFragment listOfFiles
= getListOfFilesFragment();
634 if (mDualPane
|| getSecondFragment() == null
) {
635 if (listOfFiles
!= null
) { // should never be null, indeed
636 if (mDirectories
.getCount() <= 1) {
640 int levelsUp
= listOfFiles
.onBrowseUp();
641 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
646 if (listOfFiles
!= null
) { // should never be null, indeed
647 setFile(listOfFiles
.getCurrentFile());
649 cleanSecondFragment();
654 protected void onSaveInstanceState(Bundle outState
) {
655 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
656 Log_OC
.e(TAG
, "onSaveInstanceState() start");
657 super.onSaveInstanceState(outState
);
658 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
659 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
660 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
661 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
663 Log_OC
.d(TAG
, "onSaveInstanceState() end");
669 protected void onResume() {
671 Log_OC
.e(TAG
, "onResume() start");
673 // refresh list of files
674 refreshListOfFilesFragment();
676 // Listen for sync messages
677 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
678 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
679 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
680 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
681 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
682 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
683 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
684 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
686 // Listen for upload messages
687 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
688 mUploadFinishReceiver
= new UploadFinishReceiver();
689 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
691 // Listen for download messages
692 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
693 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
694 mDownloadFinishReceiver
= new DownloadFinishReceiver();
695 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
697 Log_OC
.d(TAG
, "onResume() end");
702 protected void onPause() {
703 Log_OC
.e(TAG
, "onPause() start");
704 if (mSyncBroadcastReceiver
!= null
) {
705 unregisterReceiver(mSyncBroadcastReceiver
);
706 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
707 mSyncBroadcastReceiver
= null
;
709 if (mUploadFinishReceiver
!= null
) {
710 unregisterReceiver(mUploadFinishReceiver
);
711 mUploadFinishReceiver
= null
;
713 if (mDownloadFinishReceiver
!= null
) {
714 unregisterReceiver(mDownloadFinishReceiver
);
715 mDownloadFinishReceiver
= null
;
719 Log_OC
.d(TAG
, "onPause() end");
725 protected Dialog
onCreateDialog(int id
) {
726 Dialog dialog
= null
;
727 AlertDialog
.Builder builder
;
729 case DIALOG_SHORT_WAIT
: {
730 ProgressDialog working_dialog
= new ProgressDialog(this);
731 working_dialog
.setMessage(getResources().getString(
732 R
.string
.wait_a_moment
));
733 working_dialog
.setIndeterminate(true
);
734 working_dialog
.setCancelable(false
);
735 dialog
= working_dialog
;
738 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
740 String
[] items
= null
;
742 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
743 getString(R
.string
.actionbar_upload_from_apps
),
744 getString(R
.string
.actionbar_failed_instant_upload
) };
746 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
747 getString(R
.string
.actionbar_upload_from_apps
) };
749 if (InstantUploadActivity
.IS_ENABLED
)
754 builder
= new AlertDialog
.Builder(this);
755 builder
.setTitle(R
.string
.actionbar_upload
);
756 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
757 public void onClick(DialogInterface dialog
, int item
) {
760 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
761 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
762 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
764 // TODO create and handle new fragment
765 // LocalFileListFragment
767 } else if (item
== 1) {
768 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
769 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
770 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
771 ACTION_SELECT_CONTENT_FROM_APPS
);
772 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
773 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
774 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
775 startActivity(action
);
779 dialog
= builder
.create();
782 case DIALOG_CERT_NOT_SAVED
: {
783 builder
= new AlertDialog
.Builder(this);
784 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
785 builder
.setCancelable(false
);
786 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
788 public void onClick(DialogInterface dialog
, int which
) {
792 dialog
= builder
.create();
804 * Translates a content URI of an image to a physical path
806 * @param uri The URI to resolve
807 * @return The path to the image or null if it could not be found
809 public String
getPath(Uri uri
) {
810 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
811 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
812 if (cursor
!= null
) {
813 int column_index
= cursor
814 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
815 cursor
.moveToFirst();
816 return cursor
.getString(column_index
);
822 * Pushes a directory to the drop down list
823 * @param directory to push
824 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
826 public void pushDirname(OCFile directory
) {
827 if(!directory
.isFolder()){
828 throw new IllegalArgumentException("Only directories may be pushed!");
830 mDirectories
.insert(directory
.getFileName(), 0);
835 * Pops a directory name from the drop down list
836 * @return True, unless the stack is empty
838 public boolean popDirname() {
839 mDirectories
.remove(mDirectories
.getItem(0));
840 return !mDirectories
.isEmpty();
843 // Custom array adapter to override text colors
844 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
846 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
850 public View
getView(int position
, View convertView
, ViewGroup parent
) {
851 View v
= super.getView(position
, convertView
, parent
);
853 ((TextView
) v
).setTextColor(getResources().getColorStateList(
854 android
.R
.color
.white
));
856 fixRoot((TextView
) v
);
860 public View
getDropDownView(int position
, View convertView
,
862 View v
= super.getDropDownView(position
, convertView
, parent
);
864 ((TextView
) v
).setTextColor(getResources().getColorStateList(
865 android
.R
.color
.white
));
867 fixRoot((TextView
) v
);
871 private void fixRoot(TextView v
) {
872 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
873 v
.setText(R
.string
.default_display_name_for_root_folder
);
879 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
882 * {@link BroadcastReceiver} to enable syncing feedback in UI
885 public void onReceive(Context context
, Intent intent
) {
887 String event
= intent
.getAction();
888 Log_OC
.d(TAG
, "Received broadcast " + event
);
889 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
890 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
891 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
892 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
896 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
897 mSyncInProgress
= true
;
900 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
901 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
903 if (currentDir
== null
) {
904 // current folder was removed from the server
905 Toast
.makeText( FileDisplayActivity
.this,
906 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
912 if (currentFile
== null
&& !getFile().isFolder()) {
913 // currently selected file was removed in the server, and now we know it
914 cleanSecondFragment();
915 currentFile
= currentDir
;
918 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
919 OCFileListFragment fileListFragment
= getListOfFilesFragment();
920 if (fileListFragment
!= null
) {
921 fileListFragment
.listDirectory(currentDir
);
924 setFile(currentFile
);
927 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
929 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
931 /// TODO refactor and make common
932 synchResult
!= null
&& !synchResult
.isSuccess() &&
933 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
934 synchResult
.isIdPRedirection() ||
935 (synchResult
.isException() && synchResult
.getException()
936 instanceof AuthenticatorException
))) {
938 OwnCloudClient client
= null
;
940 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
944 // TODO get rid of these exceptions
945 } catch (AccountNotFoundException e
) {
947 } catch (AuthenticatorException e
) {
949 } catch (OperationCanceledException e
) {
951 } catch (IOException e
) {
955 if (client
!= null
) {
956 OwnCloudCredentials cred
= client
.getCredentials();
958 AccountManager am
= AccountManager
.get(context
);
959 if (cred
.authTokenExpires()) {
960 am
.invalidateAuthToken(
965 am
.clearPassword(getAccount());
970 requestCredentialsUpdate();
974 removeStickyBroadcast(intent
);
975 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
976 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
980 if (synchResult
!= null
) {
981 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
982 mLastSslUntrustedServerResult
= synchResult
;
985 } catch (RuntimeException e
) {
986 // avoid app crashes after changing the serial id of RemoteOperationResult
987 // in owncloud library with broadcast notifications pending to process
988 removeStickyBroadcast(intent
);
995 * Once the file upload has finished -> update view
997 private class UploadFinishReceiver
extends BroadcastReceiver
{
999 * Once the file upload has finished -> update view
1000 * @author David A. Velasco
1001 * {@link BroadcastReceiver} to enable upload feedback in UI
1004 public void onReceive(Context context
, Intent intent
) {
1005 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1006 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1007 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1008 OCFile currentDir
= getCurrentDir();
1009 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1010 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1012 if (sameAccount
&& isDescendant
) {
1013 refreshListOfFilesFragment();
1016 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1017 boolean renamedInUpload
= getFile().getRemotePath().
1018 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1019 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1021 FileFragment details
= getSecondFragment();
1022 boolean detailFragmentIsShown
= (details
!= null
&&
1023 details
instanceof FileDetailFragment
);
1025 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1026 if (uploadWasFine
) {
1027 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1029 if (renamedInUpload
) {
1030 String newName
= (new File(uploadedRemotePath
)).getName();
1031 Toast msg
= Toast
.makeText(
1034 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1039 if (uploadWasFine
|| getFile().fileExists()) {
1040 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1042 cleanSecondFragment();
1045 // Force the preview if the file is an image
1046 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1047 startImagePreview(getFile());
1048 } // TODO what about other kind of previews?
1051 removeStickyBroadcast(intent
);
1059 * Class waiting for broadcast events from the {@link FielDownloader} service.
1061 * Updates the UI when a download is started or finished, provided that it is relevant for the
1064 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1066 public void onReceive(Context context
, Intent intent
) {
1067 boolean sameAccount
= isSameAccount(context
, intent
);
1068 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1069 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1071 if (sameAccount
&& isDescendant
) {
1072 refreshListOfFilesFragment();
1073 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1076 if (mWaitingToSend
!= null
) {
1077 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1078 if (mWaitingToSend
.isDown()) {
1079 sendDownloadedFile();
1083 removeStickyBroadcast(intent
);
1086 private boolean isDescendant(String downloadedRemotePath
) {
1087 OCFile currentDir
= getCurrentDir();
1088 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1091 private boolean isSameAccount(Context context
, Intent intent
) {
1092 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1093 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1098 public void browseToRoot() {
1099 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1100 if (listOfFiles
!= null
) { // should never be null, indeed
1101 while (mDirectories
.getCount() > 1) {
1104 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1105 listOfFiles
.listDirectory(root
);
1106 setFile(listOfFiles
.getCurrentFile());
1107 startSyncFolderOperation(root
);
1109 cleanSecondFragment();
1113 public void browseTo(OCFile folder
) {
1114 if (folder
== null
|| !folder
.isFolder()) {
1115 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1117 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1118 if (listOfFiles
!= null
) {
1119 setNavigationListWithFolder(folder
);
1120 listOfFiles
.listDirectory(folder
);
1121 setFile(listOfFiles
.getCurrentFile());
1122 startSyncFolderOperation(folder
);
1124 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1126 cleanSecondFragment();
1133 * Updates action bar and second fragment, if in dual pane mode.
1136 public void onBrowsedDownTo(OCFile directory
) {
1137 pushDirname(directory
);
1138 cleanSecondFragment();
1141 startSyncFolderOperation(directory
);
1146 * Shows the information of the {@link OCFile} received as a
1147 * parameter in the second fragment.
1149 * @param file {@link OCFile} whose details will be shown
1152 public void showDetails(OCFile file
) {
1153 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1154 setSecondFragment(detailFragment
);
1155 updateFragmentsVisibility(true
);
1156 updateNavigationElementsInActionBar(file
);
1164 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1165 ActionBar actionBar
= getSupportActionBar();
1166 if (chosenFile
== null
|| mDualPane
) {
1167 // only list of files - set for browsing through folders
1168 OCFile currentDir
= getCurrentDir();
1169 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1170 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1171 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1173 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1175 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1176 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1179 actionBar
.setDisplayHomeAsUpEnabled(true
);
1180 actionBar
.setDisplayShowTitleEnabled(true
);
1181 actionBar
.setTitle(chosenFile
.getFileName());
1182 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1188 protected ServiceConnection
newTransferenceServiceConnection() {
1189 return new ListServiceConnection();
1192 /** Defines callbacks for service binding, passed to bindService() */
1193 private class ListServiceConnection
implements ServiceConnection
{
1196 public void onServiceConnected(ComponentName component
, IBinder service
) {
1197 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1198 Log_OC
.d(TAG
, "Download service connected");
1199 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1200 if (mWaitingToPreview
!= null
)
1201 if (getStorageManager() != null
) {
1202 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1203 if (!mWaitingToPreview
.isDown()) {
1204 requestForDownload();
1208 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1209 Log_OC
.d(TAG
, "Upload service connected");
1210 mUploaderBinder
= (FileUploaderBinder
) service
;
1214 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1215 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1216 if (listOfFiles
!= null
) {
1217 listOfFiles
.listDirectory();
1219 FileFragment secondFragment
= getSecondFragment();
1220 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1221 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1222 detailFragment
.listenForTransferProgress();
1223 detailFragment
.updateFileDetails(false
, false
);
1228 public void onServiceDisconnected(ComponentName component
) {
1229 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1230 Log_OC
.d(TAG
, "Download service disconnected");
1231 mDownloaderBinder
= null
;
1232 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1233 Log_OC
.d(TAG
, "Upload service disconnected");
1234 mUploaderBinder
= null
;
1242 * Launch an intent to request the PIN code to the user before letting him use the app
1244 private void requestPinCode() {
1245 boolean pinStart
= false
;
1246 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1247 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1249 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1250 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1257 public void onSavedCertificate() {
1258 startSyncFolderOperation(getCurrentDir());
1263 public void onFailedSavingCertificate() {
1264 showDialog(DIALOG_CERT_NOT_SAVED
);
1268 public void onCancelCertificate() {
1273 * Updates the view associated to the activity after the finish of some operation over files
1274 * in the current account.
1276 * @param operation Removal operation performed.
1277 * @param result Result of the removal.
1280 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1281 super.onRemoteOperationFinish(operation
, result
);
1283 if (operation
instanceof RemoveFileOperation
) {
1284 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1286 } else if (operation
instanceof RenameFileOperation
) {
1287 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1289 } else if (operation
instanceof SynchronizeFileOperation
) {
1290 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1292 } else if (operation
instanceof CreateFolderOperation
) {
1293 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1295 } else if (operation
instanceof CreateShareOperation
) {
1296 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1298 } else if (operation
instanceof UnshareLinkOperation
) {
1299 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1306 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1307 if (result
.isSuccess()) {
1308 refreshShowDetails();
1309 refreshListOfFilesFragment();
1314 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1315 if (result
.isSuccess()) {
1316 refreshShowDetails();
1317 refreshListOfFilesFragment();
1319 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1320 cleanSecondFragment();
1321 refreshListOfFilesFragment();
1325 private void refreshShowDetails() {
1326 FileFragment details
= getSecondFragment();
1327 if (details
!= null
) {
1328 OCFile file
= details
.getFile();
1330 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1331 if (details
instanceof PreviewMediaFragment
) {
1332 // Refresh OCFile of the fragment
1333 ((PreviewMediaFragment
) details
).updateFile(file
);
1338 invalidateOptionsMenu();
1343 * Updates the view associated to the activity after the finish of an operation trying to remove a
1346 * @param operation Removal operation performed.
1347 * @param result Result of the removal.
1349 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1350 dismissLoadingDialog();
1352 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1356 if (result
.isSuccess()) {
1357 OCFile removedFile
= operation
.getFile();
1358 FileFragment second
= getSecondFragment();
1359 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1360 if (second
instanceof PreviewMediaFragment
) {
1361 ((PreviewMediaFragment
)second
).stopPreview(true
);
1363 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1364 cleanSecondFragment();
1366 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1367 refreshListOfFilesFragment();
1369 invalidateOptionsMenu();
1371 if (result
.isSslRecoverableException()) {
1372 mLastSslUntrustedServerResult
= result
;
1373 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1380 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1382 * @param operation Creation operation performed.
1383 * @param result Result of the creation.
1385 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1386 if (result
.isSuccess()) {
1387 dismissLoadingDialog();
1388 refreshListOfFilesFragment();
1390 dismissLoadingDialog();
1392 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1393 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1397 } catch (NotFoundException e
) {
1398 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1405 * Updates the view associated to the activity after the finish of an operation trying to rename a
1408 * @param operation Renaming operation performed.
1409 * @param result Result of the renaming.
1411 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1412 dismissLoadingDialog();
1413 OCFile renamedFile
= operation
.getFile();
1414 if (result
.isSuccess()) {
1415 FileFragment details
= getSecondFragment();
1416 if (details
!= null
) {
1417 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1418 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1419 showDetails(renamedFile
);
1421 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1422 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1423 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1424 int position
= ((PreviewMediaFragment
)details
).getPosition();
1425 startMediaPreview(renamedFile
, position
, true
);
1427 getFileOperationsHelper().openFile(renamedFile
);
1432 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1433 refreshListOfFilesFragment();
1437 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1441 if (result
.isSslRecoverableException()) {
1442 mLastSslUntrustedServerResult
= result
;
1443 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1448 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1449 dismissLoadingDialog();
1450 OCFile syncedFile
= operation
.getLocalFile();
1451 if (!result
.isSuccess()) {
1452 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1453 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1454 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1455 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1461 if (operation
.transferWasRequested()) {
1462 onTransferStateChanged(syncedFile
, true
, true
);
1465 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1477 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1478 refreshListOfFilesFragment();
1479 FileFragment details
= getSecondFragment();
1480 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1481 if (downloading
|| uploading
) {
1482 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1484 if (!file
.fileExists()) {
1485 cleanSecondFragment();
1487 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1495 private void requestForDownload() {
1496 Account account
= getAccount();
1497 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1498 Intent i
= new Intent(this, FileDownloader
.class);
1499 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1500 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1506 private OCFile
getCurrentDir() {
1507 OCFile file
= getFile();
1509 if (file
.isFolder()) {
1511 } else if (getStorageManager() != null
) {
1512 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1513 return getStorageManager().getFileByPath(parentPath
);
1519 public void startSyncFolderOperation(OCFile folder
) {
1520 long currentSyncTime
= System
.currentTimeMillis();
1522 mSyncInProgress
= true
;
1524 // perform folder synchronization
1525 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1528 getFileOperationsHelper().isSharedSupported(),
1529 getStorageManager(),
1531 getApplicationContext()
1533 synchFolderOp
.execute(getAccount(), this, null
, null
);
1535 setSupportProgressBarIndeterminateVisibility(true
);
1539 * Show untrusted cert dialog
1541 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1542 // Show a dialog with the certificate info
1543 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1544 FragmentManager fm
= getSupportFragmentManager();
1545 FragmentTransaction ft
= fm
.beginTransaction();
1546 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1549 private void requestForDownload(OCFile file
) {
1550 Account account
= getAccount();
1551 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1552 Intent i
= new Intent(this, FileDownloader
.class);
1553 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1554 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1559 private void sendDownloadedFile(){
1560 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1561 mWaitingToSend
= null
;
1566 * Requests the download of the received {@link OCFile} , updates the UI
1567 * to monitor the download progress and prepares the activity to send the file
1568 * when the download finishes.
1570 * @param file {@link OCFile} to download and preview.
1572 public void startDownloadForSending(OCFile file
) {
1573 mWaitingToSend
= file
;
1574 requestForDownload(mWaitingToSend
);
1575 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1576 updateFragmentsVisibility(hasSecondFragment
);
1580 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1582 * @param file Image {@link OCFile} to show.
1584 public void startImagePreview(OCFile file
) {
1585 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1586 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1587 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1588 startActivity(showDetailsIntent
);
1593 * Stars the preview of an already down media {@link OCFile}.
1595 * @param file Media {@link OCFile} to preview.
1596 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1597 * @param autoplay When 'true', the playback will start without user interactions.
1599 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1600 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1601 setSecondFragment(mediaFragment
);
1602 updateFragmentsVisibility(true
);
1603 updateNavigationElementsInActionBar(file
);
1608 * Requests the download of the received {@link OCFile} , updates the UI
1609 * to monitor the download progress and prepares the activity to preview
1610 * or open the file when the download finishes.
1612 * @param file {@link OCFile} to download and preview.
1614 public void startDownloadForPreview(OCFile file
) {
1615 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1616 setSecondFragment(detailFragment
);
1617 mWaitingToPreview
= file
;
1618 requestForDownload();
1619 updateFragmentsVisibility(true
);
1620 updateNavigationElementsInActionBar(file
);
1625 public void cancelTransference(OCFile file
) {
1626 getFileOperationsHelper().cancelTransference(file
);
1627 if (mWaitingToPreview
!= null
&&
1628 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1629 mWaitingToPreview
= null
;
1631 if (mWaitingToSend
!= null
&&
1632 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1633 mWaitingToSend
= null
;
1635 onTransferStateChanged(file
, false
, false
);