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
.OwnCloudAccount
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
78 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
79 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
80 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
83 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
84 import com
.owncloud
.android
.operations
.CreateShareOperation
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
89 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
94 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
101 import com
.owncloud
.android
.utils
.DisplayUtils
;
102 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
103 import com
.owncloud
.android
.utils
.Log_OC
;
107 * Displays, what files the user has available in his ownCloud.
109 * @author Bartek Przybylski
110 * @author David A. Velasco
113 public class FileDisplayActivity
extends HookActivity
implements
114 FileFragment
.ContainerActivity
, OnNavigationListener
, OnSslUntrustedCertListener
{
116 private ArrayAdapter
<String
> mDirectories
;
118 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
119 private UploadFinishReceiver mUploadFinishReceiver
;
120 private DownloadFinishReceiver mDownloadFinishReceiver
;
121 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
123 private boolean mDualPane
;
124 private View mLeftFragmentContainer
;
125 private View mRightFragmentContainer
;
127 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
128 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
129 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
131 public static final int DIALOG_SHORT_WAIT
= 0;
132 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
133 private static final int DIALOG_CERT_NOT_SAVED
= 2;
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
140 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
142 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
143 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
145 private OCFile mWaitingToPreview
;
147 private boolean mSyncInProgress
= false
;
149 private String DIALOG_UNTRUSTED_CERT
;
151 private OCFile mWaitingToSend
;
154 protected void onCreate(Bundle savedInstanceState
) {
155 Log_OC
.d(TAG
, "onCreate() start");
156 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
158 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
160 // PIN CODE request ; best location is to decide, let's try this first
161 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
163 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
167 /// grant that FileObserverService is watching favourite files
168 if (savedInstanceState
!= null
) {
169 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
170 startService(initObserversIntent
);
173 /// Load of saved instance state
174 if(savedInstanceState
!= null
) {
175 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
180 mWaitingToPreview
= null
;
181 mSyncInProgress
= false
;
182 mWaitingToSend
= null
;
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
189 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
190 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
191 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
192 if (savedInstanceState
== null
) {
193 createMinFragments();
197 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
198 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
199 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
201 Log_OC
.d(TAG
, "onCreate() end");
205 protected void onStart() {
207 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
211 protected void onDestroy() {
216 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
219 protected void onAccountSet(boolean stateWasRecovered
) {
220 super.onAccountSet(stateWasRecovered
);
221 if (getAccount() != null
) {
222 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
223 OCFile file
= getFile();
224 // get parent from path
225 String parentPath
= "";
227 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
228 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
229 // get parent from path
230 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
231 if (getStorageManager().getFileByPath(parentPath
) == null
)
232 file
= null
; // not able to know the directory where the file is uploading
234 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
238 // fall back to root folder
239 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
242 setNavigationListWithFolder(file
);
244 if (!stateWasRecovered
) {
245 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
246 initFragmentsWithFile();
247 if (file
.isFolder()) {
248 startSyncFolderOperation(file
);
252 updateFragmentsVisibility(!file
.isFolder());
253 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
259 private void setNavigationListWithFolder(OCFile file
) {
260 mDirectories
.clear();
261 OCFile fileIt
= file
;
263 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
264 if (fileIt
.isFolder()) {
265 mDirectories
.add(fileIt
.getFileName());
267 // get parent from path
268 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
269 fileIt
= getStorageManager().getFileByPath(parentPath
);
271 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
275 private void createMinFragments() {
276 OCFileListFragment listOfFiles
= new OCFileListFragment();
277 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
278 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
279 transaction
.commit();
282 private void initFragmentsWithFile() {
283 if (getAccount() != null
&& getFile() != null
) {
285 OCFileListFragment listOfFiles
= getListOfFilesFragment();
286 if (listOfFiles
!= null
) {
287 listOfFiles
.listDirectory(getCurrentDir());
289 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
293 OCFile file
= getFile();
294 Fragment secondFragment
= chooseInitialSecondFragment(file
);
295 if (secondFragment
!= null
) {
296 setSecondFragment(secondFragment
);
297 updateFragmentsVisibility(true
);
298 updateNavigationElementsInActionBar(file
);
301 cleanSecondFragment();
305 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
306 if (getAccount() == null
) {
307 Log
.wtf(TAG
, "\t account is NULL");
309 if (getFile() == null
) {
310 Log
.wtf(TAG
, "\t file is NULL");
315 private Fragment
chooseInitialSecondFragment(OCFile file
) {
316 Fragment secondFragment
= null
;
317 if (file
!= null
&& !file
.isFolder()) {
318 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
319 && file
.getLastSyncDateForProperties() > 0 // temporal fix
321 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
322 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
323 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
326 secondFragment
= new FileDetailFragment(file
, getAccount());
329 return secondFragment
;
334 * Replaces the second fragment managed by the activity with the received as
337 * Assumes never will be more than two fragments managed at the same time.
339 * @param fragment New second Fragment to set.
341 private void setSecondFragment(Fragment fragment
) {
342 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
343 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
344 transaction
.commit();
348 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
350 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
351 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
353 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
354 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
357 } else if (existsSecondFragment
) {
358 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
359 mLeftFragmentContainer
.setVisibility(View
.GONE
);
361 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
362 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
366 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
369 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
370 mRightFragmentContainer
.setVisibility(View
.GONE
);
376 private OCFileListFragment
getListOfFilesFragment() {
377 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
378 if (listOfFiles
!= null
) {
379 return (OCFileListFragment
)listOfFiles
;
381 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
385 public FileFragment
getSecondFragment() {
386 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
387 if (second
!= null
) {
388 return (FileFragment
)second
;
393 protected void cleanSecondFragment() {
394 Fragment second
= getSecondFragment();
395 if (second
!= null
) {
396 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
400 updateFragmentsVisibility(false
);
401 updateNavigationElementsInActionBar(null
);
404 protected void refreshListOfFilesFragment() {
405 OCFileListFragment fileListFragment
= getListOfFilesFragment();
406 if (fileListFragment
!= null
) {
407 fileListFragment
.listDirectory();
411 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
412 FileFragment secondFragment
= getSecondFragment();
413 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
414 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
415 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
416 OCFile fileInFragment
= detailsFragment
.getFile();
417 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
418 // the user browsed to other file ; forget the automatic preview
419 mWaitingToPreview
= null
;
421 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
422 // grant that the right panel updates the progress bar
423 detailsFragment
.listenForTransferProgress();
424 detailsFragment
.updateFileDetails(true
, false
);
426 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
427 // update the right panel
428 boolean detailsFragmentChanged
= false
;
431 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
432 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
433 startMediaPreview(mWaitingToPreview
, 0, true
);
434 detailsFragmentChanged
= true
;
436 getFileOperationsHelper().openFile(mWaitingToPreview
);
439 mWaitingToPreview
= null
;
441 if (!detailsFragmentChanged
) {
442 detailsFragment
.updateFileDetails(false
, (success
));
449 public boolean onCreateOptionsMenu(Menu menu
) {
450 MenuInflater inflater
= getSherlock().getMenuInflater();
451 inflater
.inflate(R
.menu
.main_menu
, menu
);
456 public boolean onOptionsItemSelected(MenuItem item
) {
457 boolean retval
= true
;
458 switch (item
.getItemId()) {
459 case R
.id
.action_create_dir
: {
460 CreateFolderDialogFragment dialog
=
461 CreateFolderDialogFragment
.newInstance(getCurrentDir());
462 dialog
.show(getSupportFragmentManager(), "createdirdialog");
465 case R
.id
.action_sync_account
: {
466 startSynchronization();
469 case R
.id
.action_upload
: {
470 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
473 case R
.id
.action_settings
: {
474 Intent settingsIntent
= new Intent(this, Preferences
.class);
475 startActivity(settingsIntent
);
478 case android
.R
.id
.home
: {
479 FileFragment second
= getSecondFragment();
480 OCFile currentDir
= getCurrentDir();
481 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
482 (second
!= null
&& second
.getFile() != null
)) {
489 retval
= super.onOptionsItemSelected(item
);
494 private void startSynchronization() {
495 Log_OC
.e(TAG
, "Got to start sync");
496 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
497 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
498 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
499 Bundle bundle
= new Bundle();
500 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
501 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
502 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
503 ContentResolver
.requestSync(
505 MainApp
.getAuthority(), bundle
);
507 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
508 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
509 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
510 builder
.setExpedited(true
);
511 builder
.setManual(true
);
513 SyncRequest request
= builder
.build();
514 ContentResolver
.requestSync(request
);
520 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
521 if (itemPosition
!= 0) {
522 String targetPath
= "";
523 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
524 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
526 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
527 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
528 if (targetFolder
!= null
) {
529 browseTo(targetFolder
);
532 // the next operation triggers a new call to this method, but it's necessary to
533 // ensure that the name exposed in the action bar is the current directory when the
534 // user selected it in the navigation list
535 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
536 getSupportActionBar().setSelectedNavigationItem(0);
542 * Called, when the user selected something for uploading
544 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
545 super.onActivityResult(requestCode
, resultCode
, data
);
547 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
548 requestSimpleUpload(data
, resultCode
);
550 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
551 requestMultipleUpload(data
, resultCode
);
556 private void requestMultipleUpload(Intent data
, int resultCode
) {
557 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
558 if (filePaths
!= null
) {
559 String
[] remotePaths
= new String
[filePaths
.length
];
560 String remotePathBase
= "";
561 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
562 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
564 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
565 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
566 for (int j
= 0; j
< remotePaths
.length
; j
++) {
567 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
570 Intent i
= new Intent(this, FileUploader
.class);
571 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
572 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
573 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
574 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
575 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
576 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
580 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
581 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
588 private void requestSimpleUpload(Intent data
, int resultCode
) {
589 String filepath
= null
;
591 Uri selectedImageUri
= data
.getData();
593 String filemanagerstring
= selectedImageUri
.getPath();
594 String selectedImagePath
= getPath(selectedImageUri
);
596 if (selectedImagePath
!= null
)
597 filepath
= selectedImagePath
;
599 filepath
= filemanagerstring
;
601 } catch (Exception e
) {
602 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
606 if (filepath
== null
) {
607 Log_OC
.e(TAG
, "Couldnt resolve path to file");
608 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
614 Intent i
= new Intent(this, FileUploader
.class);
615 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
617 String remotepath
= new String();
618 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
619 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
621 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
622 remotepath
+= OCFile
.PATH_SEPARATOR
;
623 remotepath
+= new File(filepath
).getName();
625 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
626 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
627 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
628 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
629 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
634 public void onBackPressed() {
635 OCFileListFragment listOfFiles
= getListOfFilesFragment();
636 if (mDualPane
|| getSecondFragment() == null
) {
637 if (listOfFiles
!= null
) { // should never be null, indeed
638 if (mDirectories
.getCount() <= 1) {
642 int levelsUp
= listOfFiles
.onBrowseUp();
643 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
648 if (listOfFiles
!= null
) { // should never be null, indeed
649 setFile(listOfFiles
.getCurrentFile());
651 cleanSecondFragment();
656 protected void onSaveInstanceState(Bundle outState
) {
657 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
658 Log_OC
.e(TAG
, "onSaveInstanceState() start");
659 super.onSaveInstanceState(outState
);
660 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
661 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
662 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
663 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
665 Log_OC
.d(TAG
, "onSaveInstanceState() end");
671 protected void onResume() {
673 Log_OC
.e(TAG
, "onResume() start");
675 // refresh list of files
676 refreshListOfFilesFragment();
678 // Listen for sync messages
679 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
680 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
681 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
682 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
683 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
684 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
685 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
686 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
688 // Listen for upload messages
689 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
690 mUploadFinishReceiver
= new UploadFinishReceiver();
691 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
693 // Listen for download messages
694 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
695 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
696 mDownloadFinishReceiver
= new DownloadFinishReceiver();
697 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
699 Log_OC
.d(TAG
, "onResume() end");
704 protected void onPause() {
705 Log_OC
.e(TAG
, "onPause() start");
706 if (mSyncBroadcastReceiver
!= null
) {
707 unregisterReceiver(mSyncBroadcastReceiver
);
708 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
709 mSyncBroadcastReceiver
= null
;
711 if (mUploadFinishReceiver
!= null
) {
712 unregisterReceiver(mUploadFinishReceiver
);
713 mUploadFinishReceiver
= null
;
715 if (mDownloadFinishReceiver
!= null
) {
716 unregisterReceiver(mDownloadFinishReceiver
);
717 mDownloadFinishReceiver
= null
;
721 Log_OC
.d(TAG
, "onPause() end");
727 protected Dialog
onCreateDialog(int id
) {
728 Dialog dialog
= null
;
729 AlertDialog
.Builder builder
;
731 case DIALOG_SHORT_WAIT
: {
732 ProgressDialog working_dialog
= new ProgressDialog(this);
733 working_dialog
.setMessage(getResources().getString(
734 R
.string
.wait_a_moment
));
735 working_dialog
.setIndeterminate(true
);
736 working_dialog
.setCancelable(false
);
737 dialog
= working_dialog
;
740 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
742 String
[] items
= null
;
744 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
745 getString(R
.string
.actionbar_upload_from_apps
),
746 getString(R
.string
.actionbar_failed_instant_upload
) };
748 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
749 getString(R
.string
.actionbar_upload_from_apps
) };
751 if (InstantUploadActivity
.IS_ENABLED
)
756 builder
= new AlertDialog
.Builder(this);
757 builder
.setTitle(R
.string
.actionbar_upload
);
758 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
759 public void onClick(DialogInterface dialog
, int item
) {
762 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
763 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
764 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
766 // TODO create and handle new fragment
767 // LocalFileListFragment
769 } else if (item
== 1) {
770 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
771 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
772 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
773 ACTION_SELECT_CONTENT_FROM_APPS
);
774 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
775 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
776 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
777 startActivity(action
);
781 dialog
= builder
.create();
784 case DIALOG_CERT_NOT_SAVED
: {
785 builder
= new AlertDialog
.Builder(this);
786 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
787 builder
.setCancelable(false
);
788 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
790 public void onClick(DialogInterface dialog
, int which
) {
794 dialog
= builder
.create();
806 * Translates a content URI of an image to a physical path
808 * @param uri The URI to resolve
809 * @return The path to the image or null if it could not be found
811 public String
getPath(Uri uri
) {
812 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
813 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
814 if (cursor
!= null
) {
815 int column_index
= cursor
816 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
817 cursor
.moveToFirst();
818 return cursor
.getString(column_index
);
824 * Pushes a directory to the drop down list
825 * @param directory to push
826 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
828 public void pushDirname(OCFile directory
) {
829 if(!directory
.isFolder()){
830 throw new IllegalArgumentException("Only directories may be pushed!");
832 mDirectories
.insert(directory
.getFileName(), 0);
837 * Pops a directory name from the drop down list
838 * @return True, unless the stack is empty
840 public boolean popDirname() {
841 mDirectories
.remove(mDirectories
.getItem(0));
842 return !mDirectories
.isEmpty();
845 // Custom array adapter to override text colors
846 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
848 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
852 public View
getView(int position
, View convertView
, ViewGroup parent
) {
853 View v
= super.getView(position
, convertView
, parent
);
855 ((TextView
) v
).setTextColor(getResources().getColorStateList(
856 android
.R
.color
.white
));
858 fixRoot((TextView
) v
);
862 public View
getDropDownView(int position
, View convertView
,
864 View v
= super.getDropDownView(position
, convertView
, parent
);
866 ((TextView
) v
).setTextColor(getResources().getColorStateList(
867 android
.R
.color
.white
));
869 fixRoot((TextView
) v
);
873 private void fixRoot(TextView v
) {
874 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
875 v
.setText(R
.string
.default_display_name_for_root_folder
);
881 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
884 * {@link BroadcastReceiver} to enable syncing feedback in UI
887 public void onReceive(Context context
, Intent intent
) {
889 String event
= intent
.getAction();
890 Log_OC
.d(TAG
, "Received broadcast " + event
);
891 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
892 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
893 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
894 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
898 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
899 mSyncInProgress
= true
;
902 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
903 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
905 if (currentDir
== null
) {
906 // current folder was removed from the server
907 Toast
.makeText( FileDisplayActivity
.this,
908 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
914 if (currentFile
== null
&& !getFile().isFolder()) {
915 // currently selected file was removed in the server, and now we know it
916 cleanSecondFragment();
917 currentFile
= currentDir
;
920 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
921 OCFileListFragment fileListFragment
= getListOfFilesFragment();
922 if (fileListFragment
!= null
) {
923 fileListFragment
.listDirectory(currentDir
);
926 setFile(currentFile
);
929 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
931 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
933 /// TODO refactor and make common
934 synchResult
!= null
&& !synchResult
.isSuccess() &&
935 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
936 synchResult
.isIdPRedirection() ||
937 (synchResult
.isException() && synchResult
.getException()
938 instanceof AuthenticatorException
))) {
940 OwnCloudClient client
= null
;
942 OwnCloudAccount ocAccount
=
943 new OwnCloudAccount(getAccount(), context
);
944 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
945 removeClientFor(ocAccount
));
946 // TODO get rid of these exceptions
947 } catch (AccountNotFoundException e
) {
949 } catch (AuthenticatorException e
) {
951 } catch (OperationCanceledException e
) {
953 } catch (IOException e
) {
957 if (client
!= null
) {
958 OwnCloudCredentials cred
= client
.getCredentials();
960 AccountManager am
= AccountManager
.get(context
);
961 if (cred
.authTokenExpires()) {
962 am
.invalidateAuthToken(
967 am
.clearPassword(getAccount());
972 requestCredentialsUpdate();
976 removeStickyBroadcast(intent
);
977 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
978 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
982 if (synchResult
!= null
) {
983 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
984 mLastSslUntrustedServerResult
= synchResult
;
987 } catch (RuntimeException e
) {
988 // avoid app crashes after changing the serial id of RemoteOperationResult
989 // in owncloud library with broadcast notifications pending to process
990 removeStickyBroadcast(intent
);
997 * Once the file upload has finished -> update view
999 private class UploadFinishReceiver
extends BroadcastReceiver
{
1001 * Once the file upload has finished -> update view
1002 * @author David A. Velasco
1003 * {@link BroadcastReceiver} to enable upload feedback in UI
1006 public void onReceive(Context context
, Intent intent
) {
1007 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1008 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1009 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1010 OCFile currentDir
= getCurrentDir();
1011 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1012 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1014 if (sameAccount
&& isDescendant
) {
1015 refreshListOfFilesFragment();
1018 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1019 boolean renamedInUpload
= getFile().getRemotePath().
1020 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1021 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1023 FileFragment details
= getSecondFragment();
1024 boolean detailFragmentIsShown
= (details
!= null
&&
1025 details
instanceof FileDetailFragment
);
1027 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1028 if (uploadWasFine
) {
1029 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1031 if (renamedInUpload
) {
1032 String newName
= (new File(uploadedRemotePath
)).getName();
1033 Toast msg
= Toast
.makeText(
1036 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1041 if (uploadWasFine
|| getFile().fileExists()) {
1042 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1044 cleanSecondFragment();
1047 // Force the preview if the file is an image
1048 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1049 startImagePreview(getFile());
1050 } // TODO what about other kind of previews?
1053 removeStickyBroadcast(intent
);
1061 * Class waiting for broadcast events from the {@link FielDownloader} service.
1063 * Updates the UI when a download is started or finished, provided that it is relevant for the
1066 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1068 public void onReceive(Context context
, Intent intent
) {
1069 boolean sameAccount
= isSameAccount(context
, intent
);
1070 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1071 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1073 if (sameAccount
&& isDescendant
) {
1074 refreshListOfFilesFragment();
1075 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1078 if (mWaitingToSend
!= null
) {
1079 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1080 if (mWaitingToSend
.isDown()) {
1081 sendDownloadedFile();
1085 removeStickyBroadcast(intent
);
1088 private boolean isDescendant(String downloadedRemotePath
) {
1089 OCFile currentDir
= getCurrentDir();
1090 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1093 private boolean isSameAccount(Context context
, Intent intent
) {
1094 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1095 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1100 public void browseToRoot() {
1101 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1102 if (listOfFiles
!= null
) { // should never be null, indeed
1103 while (mDirectories
.getCount() > 1) {
1106 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1107 listOfFiles
.listDirectory(root
);
1108 setFile(listOfFiles
.getCurrentFile());
1109 startSyncFolderOperation(root
);
1111 cleanSecondFragment();
1115 public void browseTo(OCFile folder
) {
1116 if (folder
== null
|| !folder
.isFolder()) {
1117 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1119 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1120 if (listOfFiles
!= null
) {
1121 setNavigationListWithFolder(folder
);
1122 listOfFiles
.listDirectory(folder
);
1123 setFile(listOfFiles
.getCurrentFile());
1124 startSyncFolderOperation(folder
);
1126 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1128 cleanSecondFragment();
1135 * Updates action bar and second fragment, if in dual pane mode.
1138 public void onBrowsedDownTo(OCFile directory
) {
1139 pushDirname(directory
);
1140 cleanSecondFragment();
1143 startSyncFolderOperation(directory
);
1148 * Shows the information of the {@link OCFile} received as a
1149 * parameter in the second fragment.
1151 * @param file {@link OCFile} whose details will be shown
1154 public void showDetails(OCFile file
) {
1155 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1156 setSecondFragment(detailFragment
);
1157 updateFragmentsVisibility(true
);
1158 updateNavigationElementsInActionBar(file
);
1166 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1167 ActionBar actionBar
= getSupportActionBar();
1168 if (chosenFile
== null
|| mDualPane
) {
1169 // only list of files - set for browsing through folders
1170 OCFile currentDir
= getCurrentDir();
1171 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1172 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1173 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1175 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1177 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1178 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1181 actionBar
.setDisplayHomeAsUpEnabled(true
);
1182 actionBar
.setDisplayShowTitleEnabled(true
);
1183 actionBar
.setTitle(chosenFile
.getFileName());
1184 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1190 protected ServiceConnection
newTransferenceServiceConnection() {
1191 return new ListServiceConnection();
1194 /** Defines callbacks for service binding, passed to bindService() */
1195 private class ListServiceConnection
implements ServiceConnection
{
1198 public void onServiceConnected(ComponentName component
, IBinder service
) {
1199 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1200 Log_OC
.d(TAG
, "Download service connected");
1201 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1202 if (mWaitingToPreview
!= null
)
1203 if (getStorageManager() != null
) {
1204 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1205 if (!mWaitingToPreview
.isDown()) {
1206 requestForDownload();
1210 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1211 Log_OC
.d(TAG
, "Upload service connected");
1212 mUploaderBinder
= (FileUploaderBinder
) service
;
1216 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1217 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1218 if (listOfFiles
!= null
) {
1219 listOfFiles
.listDirectory();
1221 FileFragment secondFragment
= getSecondFragment();
1222 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1223 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1224 detailFragment
.listenForTransferProgress();
1225 detailFragment
.updateFileDetails(false
, false
);
1230 public void onServiceDisconnected(ComponentName component
) {
1231 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1232 Log_OC
.d(TAG
, "Download service disconnected");
1233 mDownloaderBinder
= null
;
1234 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1235 Log_OC
.d(TAG
, "Upload service disconnected");
1236 mUploaderBinder
= null
;
1244 * Launch an intent to request the PIN code to the user before letting him use the app
1246 private void requestPinCode() {
1247 boolean pinStart
= false
;
1248 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1249 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1251 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1252 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1259 public void onSavedCertificate() {
1260 startSyncFolderOperation(getCurrentDir());
1265 public void onFailedSavingCertificate() {
1266 showDialog(DIALOG_CERT_NOT_SAVED
);
1270 public void onCancelCertificate() {
1275 * Updates the view associated to the activity after the finish of some operation over files
1276 * in the current account.
1278 * @param operation Removal operation performed.
1279 * @param result Result of the removal.
1282 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1283 super.onRemoteOperationFinish(operation
, result
);
1285 if (operation
instanceof RemoveFileOperation
) {
1286 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1288 } else if (operation
instanceof RenameFileOperation
) {
1289 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1291 } else if (operation
instanceof SynchronizeFileOperation
) {
1292 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1294 } else if (operation
instanceof CreateFolderOperation
) {
1295 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1297 } else if (operation
instanceof CreateShareOperation
) {
1298 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1300 } else if (operation
instanceof UnshareLinkOperation
) {
1301 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1308 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1309 if (result
.isSuccess()) {
1310 refreshShowDetails();
1311 refreshListOfFilesFragment();
1316 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1317 if (result
.isSuccess()) {
1318 refreshShowDetails();
1319 refreshListOfFilesFragment();
1321 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1322 cleanSecondFragment();
1323 refreshListOfFilesFragment();
1327 private void refreshShowDetails() {
1328 FileFragment details
= getSecondFragment();
1329 if (details
!= null
) {
1330 OCFile file
= details
.getFile();
1332 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1333 if (details
instanceof PreviewMediaFragment
) {
1334 // Refresh OCFile of the fragment
1335 ((PreviewMediaFragment
) details
).updateFile(file
);
1340 invalidateOptionsMenu();
1345 * Updates the view associated to the activity after the finish of an operation trying to remove a
1348 * @param operation Removal operation performed.
1349 * @param result Result of the removal.
1351 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1352 dismissLoadingDialog();
1354 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1358 if (result
.isSuccess()) {
1359 OCFile removedFile
= operation
.getFile();
1360 FileFragment second
= getSecondFragment();
1361 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1362 if (second
instanceof PreviewMediaFragment
) {
1363 ((PreviewMediaFragment
)second
).stopPreview(true
);
1365 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1366 cleanSecondFragment();
1368 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1369 refreshListOfFilesFragment();
1371 invalidateOptionsMenu();
1373 if (result
.isSslRecoverableException()) {
1374 mLastSslUntrustedServerResult
= result
;
1375 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1382 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1384 * @param operation Creation operation performed.
1385 * @param result Result of the creation.
1387 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1388 if (result
.isSuccess()) {
1389 dismissLoadingDialog();
1390 refreshListOfFilesFragment();
1392 dismissLoadingDialog();
1394 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1395 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1399 } catch (NotFoundException e
) {
1400 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1407 * Updates the view associated to the activity after the finish of an operation trying to rename a
1410 * @param operation Renaming operation performed.
1411 * @param result Result of the renaming.
1413 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1414 dismissLoadingDialog();
1415 OCFile renamedFile
= operation
.getFile();
1416 if (result
.isSuccess()) {
1417 FileFragment details
= getSecondFragment();
1418 if (details
!= null
) {
1419 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1420 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1421 showDetails(renamedFile
);
1423 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1424 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1425 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1426 int position
= ((PreviewMediaFragment
)details
).getPosition();
1427 startMediaPreview(renamedFile
, position
, true
);
1429 getFileOperationsHelper().openFile(renamedFile
);
1434 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1435 refreshListOfFilesFragment();
1439 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1443 if (result
.isSslRecoverableException()) {
1444 mLastSslUntrustedServerResult
= result
;
1445 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1450 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1451 dismissLoadingDialog();
1452 OCFile syncedFile
= operation
.getLocalFile();
1453 if (!result
.isSuccess()) {
1454 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1455 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1456 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1457 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1463 if (operation
.transferWasRequested()) {
1464 onTransferStateChanged(syncedFile
, true
, true
);
1467 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1479 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1480 refreshListOfFilesFragment();
1481 FileFragment details
= getSecondFragment();
1482 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1483 if (downloading
|| uploading
) {
1484 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1486 if (!file
.fileExists()) {
1487 cleanSecondFragment();
1489 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1497 private void requestForDownload() {
1498 Account account
= getAccount();
1499 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1500 Intent i
= new Intent(this, FileDownloader
.class);
1501 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1502 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1508 private OCFile
getCurrentDir() {
1509 OCFile file
= getFile();
1511 if (file
.isFolder()) {
1513 } else if (getStorageManager() != null
) {
1514 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1515 return getStorageManager().getFileByPath(parentPath
);
1521 public void startSyncFolderOperation(OCFile folder
) {
1522 long currentSyncTime
= System
.currentTimeMillis();
1524 mSyncInProgress
= true
;
1526 // perform folder synchronization
1527 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1530 getFileOperationsHelper().isSharedSupported(),
1531 getStorageManager(),
1533 getApplicationContext()
1535 synchFolderOp
.execute(getAccount(), this, null
, null
);
1537 setSupportProgressBarIndeterminateVisibility(true
);
1541 * Show untrusted cert dialog
1543 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1544 // Show a dialog with the certificate info
1545 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1546 FragmentManager fm
= getSupportFragmentManager();
1547 FragmentTransaction ft
= fm
.beginTransaction();
1548 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1551 private void requestForDownload(OCFile file
) {
1552 Account account
= getAccount();
1553 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1554 Intent i
= new Intent(this, FileDownloader
.class);
1555 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1556 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1561 private void sendDownloadedFile(){
1562 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1563 mWaitingToSend
= null
;
1568 * Requests the download of the received {@link OCFile} , updates the UI
1569 * to monitor the download progress and prepares the activity to send the file
1570 * when the download finishes.
1572 * @param file {@link OCFile} to download and preview.
1574 public void startDownloadForSending(OCFile file
) {
1575 mWaitingToSend
= file
;
1576 requestForDownload(mWaitingToSend
);
1577 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1578 updateFragmentsVisibility(hasSecondFragment
);
1582 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1584 * @param file Image {@link OCFile} to show.
1586 public void startImagePreview(OCFile file
) {
1587 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1588 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1589 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1590 startActivity(showDetailsIntent
);
1595 * Stars the preview of an already down media {@link OCFile}.
1597 * @param file Media {@link OCFile} to preview.
1598 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1599 * @param autoplay When 'true', the playback will start without user interactions.
1601 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1602 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1603 setSecondFragment(mediaFragment
);
1604 updateFragmentsVisibility(true
);
1605 updateNavigationElementsInActionBar(file
);
1610 * Requests the download of the received {@link OCFile} , updates the UI
1611 * to monitor the download progress and prepares the activity to preview
1612 * or open the file when the download finishes.
1614 * @param file {@link OCFile} to download and preview.
1616 public void startDownloadForPreview(OCFile file
) {
1617 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1618 setSecondFragment(detailFragment
);
1619 mWaitingToPreview
= file
;
1620 requestForDownload();
1621 updateFragmentsVisibility(true
);
1622 updateNavigationElementsInActionBar(file
);
1627 public void cancelTransference(OCFile file
) {
1628 getFileOperationsHelper().cancelTransference(file
);
1629 if (mWaitingToPreview
!= null
&&
1630 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1631 mWaitingToPreview
= null
;
1633 if (mWaitingToSend
!= null
&&
1634 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1635 mWaitingToSend
= null
;
1637 onTransferStateChanged(file
, false
, false
);