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
) {
168 Intent observer_intent
= new Intent(this, FileObserverService
.class);
169 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
170 startService(observer_intent
);
172 /// Load of saved instance state
173 if(savedInstanceState
!= null
) {
174 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mWaitingToSend
= null
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
188 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
189 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
190 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
191 if (savedInstanceState
== null
) {
192 createMinFragments();
196 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
197 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
198 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
200 Log_OC
.d(TAG
, "onCreate() end");
204 protected void onStart() {
206 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
210 protected void onDestroy() {
215 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
218 protected void onAccountSet(boolean stateWasRecovered
) {
219 super.onAccountSet(stateWasRecovered
);
220 if (getAccount() != null
) {
221 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
222 OCFile file
= getFile();
223 // get parent from path
224 String parentPath
= "";
226 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
227 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
228 // get parent from path
229 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
230 if (getStorageManager().getFileByPath(parentPath
) == null
)
231 file
= null
; // not able to know the directory where the file is uploading
233 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
237 // fall back to root folder
238 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
241 setNavigationListWithFolder(file
);
243 if (!stateWasRecovered
) {
244 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
245 initFragmentsWithFile();
246 if (file
.isFolder()) {
247 startSyncFolderOperation(file
);
251 updateFragmentsVisibility(!file
.isFolder());
252 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
258 private void setNavigationListWithFolder(OCFile file
) {
259 mDirectories
.clear();
260 OCFile fileIt
= file
;
262 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
263 if (fileIt
.isFolder()) {
264 mDirectories
.add(fileIt
.getFileName());
266 // get parent from path
267 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
268 fileIt
= getStorageManager().getFileByPath(parentPath
);
270 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
274 private void createMinFragments() {
275 OCFileListFragment listOfFiles
= new OCFileListFragment();
276 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
277 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
278 transaction
.commit();
281 private void initFragmentsWithFile() {
282 if (getAccount() != null
&& getFile() != null
) {
284 OCFileListFragment listOfFiles
= getListOfFilesFragment();
285 if (listOfFiles
!= null
) {
286 listOfFiles
.listDirectory(getCurrentDir());
288 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
292 OCFile file
= getFile();
293 Fragment secondFragment
= chooseInitialSecondFragment(file
);
294 if (secondFragment
!= null
) {
295 setSecondFragment(secondFragment
);
296 updateFragmentsVisibility(true
);
297 updateNavigationElementsInActionBar(file
);
300 cleanSecondFragment();
304 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
305 if (getAccount() == null
) {
306 Log
.wtf(TAG
, "\t account is NULL");
308 if (getFile() == null
) {
309 Log
.wtf(TAG
, "\t file is NULL");
314 private Fragment
chooseInitialSecondFragment(OCFile file
) {
315 Fragment secondFragment
= null
;
316 if (file
!= null
&& !file
.isFolder()) {
317 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
318 && file
.getLastSyncDateForProperties() > 0 // temporal fix
320 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
321 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
322 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
325 secondFragment
= new FileDetailFragment(file
, getAccount());
328 return secondFragment
;
333 * Replaces the second fragment managed by the activity with the received as
336 * Assumes never will be more than two fragments managed at the same time.
338 * @param fragment New second Fragment to set.
340 private void setSecondFragment(Fragment fragment
) {
341 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
342 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
343 transaction
.commit();
347 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
349 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
350 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
352 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
353 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
356 } else if (existsSecondFragment
) {
357 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
358 mLeftFragmentContainer
.setVisibility(View
.GONE
);
360 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
361 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
365 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
368 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
369 mRightFragmentContainer
.setVisibility(View
.GONE
);
375 private OCFileListFragment
getListOfFilesFragment() {
376 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
377 if (listOfFiles
!= null
) {
378 return (OCFileListFragment
)listOfFiles
;
380 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
384 public FileFragment
getSecondFragment() {
385 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
386 if (second
!= null
) {
387 return (FileFragment
)second
;
392 protected void cleanSecondFragment() {
393 Fragment second
= getSecondFragment();
394 if (second
!= null
) {
395 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
399 updateFragmentsVisibility(false
);
400 updateNavigationElementsInActionBar(null
);
403 protected void refreshListOfFilesFragment() {
404 OCFileListFragment fileListFragment
= getListOfFilesFragment();
405 if (fileListFragment
!= null
) {
406 fileListFragment
.listDirectory();
410 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
411 FileFragment secondFragment
= getSecondFragment();
412 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
413 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
414 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
415 OCFile fileInFragment
= detailsFragment
.getFile();
416 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
417 // the user browsed to other file ; forget the automatic preview
418 mWaitingToPreview
= null
;
420 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
421 // grant that the right panel updates the progress bar
422 detailsFragment
.listenForTransferProgress();
423 detailsFragment
.updateFileDetails(true
, false
);
425 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
426 // update the right panel
427 boolean detailsFragmentChanged
= false
;
430 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
431 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
432 startMediaPreview(mWaitingToPreview
, 0, true
);
433 detailsFragmentChanged
= true
;
435 getFileOperationsHelper().openFile(mWaitingToPreview
);
438 mWaitingToPreview
= null
;
440 if (!detailsFragmentChanged
) {
441 detailsFragment
.updateFileDetails(false
, (success
));
448 public boolean onCreateOptionsMenu(Menu menu
) {
449 MenuInflater inflater
= getSherlock().getMenuInflater();
450 inflater
.inflate(R
.menu
.main_menu
, menu
);
455 public boolean onOptionsItemSelected(MenuItem item
) {
456 boolean retval
= true
;
457 switch (item
.getItemId()) {
458 case R
.id
.action_create_dir
: {
459 CreateFolderDialogFragment dialog
=
460 CreateFolderDialogFragment
.newInstance(getCurrentDir());
461 dialog
.show(getSupportFragmentManager(), "createdirdialog");
464 case R
.id
.action_sync_account
: {
465 startSynchronization();
468 case R
.id
.action_upload
: {
469 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
472 case R
.id
.action_settings
: {
473 Intent settingsIntent
= new Intent(this, Preferences
.class);
474 startActivity(settingsIntent
);
477 case android
.R
.id
.home
: {
478 FileFragment second
= getSecondFragment();
479 OCFile currentDir
= getCurrentDir();
480 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
481 (second
!= null
&& second
.getFile() != null
)) {
488 retval
= super.onOptionsItemSelected(item
);
493 private void startSynchronization() {
494 Log_OC
.e(TAG
, "Got to start sync");
495 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
496 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
497 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
498 Bundle bundle
= new Bundle();
499 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
500 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
501 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
502 ContentResolver
.requestSync(
504 MainApp
.getAuthority(), bundle
);
506 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
507 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
508 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
509 builder
.setExpedited(true
);
510 builder
.setManual(true
);
512 SyncRequest request
= builder
.build();
513 ContentResolver
.requestSync(request
);
519 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
520 if (itemPosition
!= 0) {
521 String targetPath
= "";
522 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
523 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
525 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
526 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
527 if (targetFolder
!= null
) {
528 browseTo(targetFolder
);
531 // the next operation triggers a new call to this method, but it's necessary to
532 // ensure that the name exposed in the action bar is the current directory when the
533 // user selected it in the navigation list
534 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
535 getSupportActionBar().setSelectedNavigationItem(0);
541 * Called, when the user selected something for uploading
543 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
544 super.onActivityResult(requestCode
, resultCode
, data
);
546 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
547 requestSimpleUpload(data
, resultCode
);
549 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
550 requestMultipleUpload(data
, resultCode
);
555 private void requestMultipleUpload(Intent data
, int resultCode
) {
556 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
557 if (filePaths
!= null
) {
558 String
[] remotePaths
= new String
[filePaths
.length
];
559 String remotePathBase
= "";
560 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
561 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
563 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
564 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
565 for (int j
= 0; j
< remotePaths
.length
; j
++) {
566 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
569 Intent i
= new Intent(this, FileUploader
.class);
570 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
571 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
572 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
573 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
574 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
575 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
579 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
580 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
587 private void requestSimpleUpload(Intent data
, int resultCode
) {
588 String filepath
= null
;
590 Uri selectedImageUri
= data
.getData();
592 String filemanagerstring
= selectedImageUri
.getPath();
593 String selectedImagePath
= getPath(selectedImageUri
);
595 if (selectedImagePath
!= null
)
596 filepath
= selectedImagePath
;
598 filepath
= filemanagerstring
;
600 } catch (Exception e
) {
601 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
605 if (filepath
== null
) {
606 Log_OC
.e(TAG
, "Couldnt resolve path to file");
607 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
613 Intent i
= new Intent(this, FileUploader
.class);
614 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
616 String remotepath
= new String();
617 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
618 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
620 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
621 remotepath
+= OCFile
.PATH_SEPARATOR
;
622 remotepath
+= new File(filepath
).getName();
624 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
625 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
626 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
627 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
628 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
633 public void onBackPressed() {
634 OCFileListFragment listOfFiles
= getListOfFilesFragment();
635 if (mDualPane
|| getSecondFragment() == null
) {
636 if (listOfFiles
!= null
) { // should never be null, indeed
637 if (mDirectories
.getCount() <= 1) {
641 int levelsUp
= listOfFiles
.onBrowseUp();
642 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
647 if (listOfFiles
!= null
) { // should never be null, indeed
648 setFile(listOfFiles
.getCurrentFile());
650 cleanSecondFragment();
655 protected void onSaveInstanceState(Bundle outState
) {
656 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
657 Log_OC
.e(TAG
, "onSaveInstanceState() start");
658 super.onSaveInstanceState(outState
);
659 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
660 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
661 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
662 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
664 Log_OC
.d(TAG
, "onSaveInstanceState() end");
670 protected void onResume() {
672 Log_OC
.e(TAG
, "onResume() start");
674 // refresh list of files
675 refreshListOfFilesFragment();
677 // Listen for sync messages
678 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
679 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
680 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
681 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
682 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
683 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
684 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
685 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
687 // Listen for upload messages
688 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
689 mUploadFinishReceiver
= new UploadFinishReceiver();
690 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
692 // Listen for download messages
693 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
694 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
695 mDownloadFinishReceiver
= new DownloadFinishReceiver();
696 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
698 Log_OC
.d(TAG
, "onResume() end");
703 protected void onPause() {
704 Log_OC
.e(TAG
, "onPause() start");
705 if (mSyncBroadcastReceiver
!= null
) {
706 unregisterReceiver(mSyncBroadcastReceiver
);
707 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
708 mSyncBroadcastReceiver
= null
;
710 if (mUploadFinishReceiver
!= null
) {
711 unregisterReceiver(mUploadFinishReceiver
);
712 mUploadFinishReceiver
= null
;
714 if (mDownloadFinishReceiver
!= null
) {
715 unregisterReceiver(mDownloadFinishReceiver
);
716 mDownloadFinishReceiver
= null
;
720 Log_OC
.d(TAG
, "onPause() end");
726 protected Dialog
onCreateDialog(int id
) {
727 Dialog dialog
= null
;
728 AlertDialog
.Builder builder
;
730 case DIALOG_SHORT_WAIT
: {
731 ProgressDialog working_dialog
= new ProgressDialog(this);
732 working_dialog
.setMessage(getResources().getString(
733 R
.string
.wait_a_moment
));
734 working_dialog
.setIndeterminate(true
);
735 working_dialog
.setCancelable(false
);
736 dialog
= working_dialog
;
739 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
741 String
[] items
= null
;
743 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
744 getString(R
.string
.actionbar_upload_from_apps
),
745 getString(R
.string
.actionbar_failed_instant_upload
) };
747 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
748 getString(R
.string
.actionbar_upload_from_apps
) };
750 if (InstantUploadActivity
.IS_ENABLED
)
755 builder
= new AlertDialog
.Builder(this);
756 builder
.setTitle(R
.string
.actionbar_upload
);
757 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
758 public void onClick(DialogInterface dialog
, int item
) {
761 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
762 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
763 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
765 // TODO create and handle new fragment
766 // LocalFileListFragment
768 } else if (item
== 1) {
769 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
770 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
771 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
772 ACTION_SELECT_CONTENT_FROM_APPS
);
773 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
774 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
775 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
776 startActivity(action
);
780 dialog
= builder
.create();
783 case DIALOG_CERT_NOT_SAVED
: {
784 builder
= new AlertDialog
.Builder(this);
785 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
786 builder
.setCancelable(false
);
787 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
789 public void onClick(DialogInterface dialog
, int which
) {
793 dialog
= builder
.create();
805 * Translates a content URI of an image to a physical path
807 * @param uri The URI to resolve
808 * @return The path to the image or null if it could not be found
810 public String
getPath(Uri uri
) {
811 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
812 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
813 if (cursor
!= null
) {
814 int column_index
= cursor
815 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
816 cursor
.moveToFirst();
817 return cursor
.getString(column_index
);
823 * Pushes a directory to the drop down list
824 * @param directory to push
825 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
827 public void pushDirname(OCFile directory
) {
828 if(!directory
.isFolder()){
829 throw new IllegalArgumentException("Only directories may be pushed!");
831 mDirectories
.insert(directory
.getFileName(), 0);
836 * Pops a directory name from the drop down list
837 * @return True, unless the stack is empty
839 public boolean popDirname() {
840 mDirectories
.remove(mDirectories
.getItem(0));
841 return !mDirectories
.isEmpty();
844 // Custom array adapter to override text colors
845 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
847 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
851 public View
getView(int position
, View convertView
, ViewGroup parent
) {
852 View v
= super.getView(position
, convertView
, parent
);
854 ((TextView
) v
).setTextColor(getResources().getColorStateList(
855 android
.R
.color
.white
));
857 fixRoot((TextView
) v
);
861 public View
getDropDownView(int position
, View convertView
,
863 View v
= super.getDropDownView(position
, convertView
, parent
);
865 ((TextView
) v
).setTextColor(getResources().getColorStateList(
866 android
.R
.color
.white
));
868 fixRoot((TextView
) v
);
872 private void fixRoot(TextView v
) {
873 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
874 v
.setText(R
.string
.default_display_name_for_root_folder
);
880 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
883 * {@link BroadcastReceiver} to enable syncing feedback in UI
886 public void onReceive(Context context
, Intent intent
) {
888 String event
= intent
.getAction();
889 Log_OC
.d(TAG
, "Received broadcast " + event
);
890 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
891 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
892 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
893 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
897 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
898 mSyncInProgress
= true
;
901 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
902 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
904 if (currentDir
== null
) {
905 // current folder was removed from the server
906 Toast
.makeText( FileDisplayActivity
.this,
907 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
913 if (currentFile
== null
&& !getFile().isFolder()) {
914 // currently selected file was removed in the server, and now we know it
915 cleanSecondFragment();
916 currentFile
= currentDir
;
919 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
920 OCFileListFragment fileListFragment
= getListOfFilesFragment();
921 if (fileListFragment
!= null
) {
922 fileListFragment
.listDirectory(currentDir
);
925 setFile(currentFile
);
928 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
930 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
932 /// TODO refactor and make common
933 synchResult
!= null
&& !synchResult
.isSuccess() &&
934 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
935 synchResult
.isIdPRedirection() ||
936 (synchResult
.isException() && synchResult
.getException()
937 instanceof AuthenticatorException
))) {
939 OwnCloudClient client
= null
;
941 OwnCloudAccount ocAccount
=
942 new OwnCloudAccount(getAccount(), context
);
943 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
944 removeClientFor(ocAccount
));
945 // TODO get rid of these exceptions
946 } catch (AccountNotFoundException e
) {
948 } catch (AuthenticatorException e
) {
950 } catch (OperationCanceledException e
) {
952 } catch (IOException e
) {
956 if (client
!= null
) {
957 OwnCloudCredentials cred
= client
.getCredentials();
959 AccountManager am
= AccountManager
.get(context
);
960 if (cred
.authTokenExpires()) {
961 am
.invalidateAuthToken(
966 am
.clearPassword(getAccount());
971 requestCredentialsUpdate();
975 removeStickyBroadcast(intent
);
976 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
977 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
981 if (synchResult
!= null
) {
982 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
983 mLastSslUntrustedServerResult
= synchResult
;
986 } catch (RuntimeException e
) {
987 // avoid app crashes after changing the serial id of RemoteOperationResult
988 // in owncloud library with broadcast notifications pending to process
989 removeStickyBroadcast(intent
);
996 * Once the file upload has finished -> update view
998 private class UploadFinishReceiver
extends BroadcastReceiver
{
1000 * Once the file upload has finished -> update view
1001 * @author David A. Velasco
1002 * {@link BroadcastReceiver} to enable upload feedback in UI
1005 public void onReceive(Context context
, Intent intent
) {
1006 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1007 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1008 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1009 OCFile currentDir
= getCurrentDir();
1010 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1011 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1013 if (sameAccount
&& isDescendant
) {
1014 refreshListOfFilesFragment();
1017 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1018 boolean renamedInUpload
= getFile().getRemotePath().
1019 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1020 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1022 FileFragment details
= getSecondFragment();
1023 boolean detailFragmentIsShown
= (details
!= null
&&
1024 details
instanceof FileDetailFragment
);
1026 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1027 if (uploadWasFine
) {
1028 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1030 if (renamedInUpload
) {
1031 String newName
= (new File(uploadedRemotePath
)).getName();
1032 Toast msg
= Toast
.makeText(
1035 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1040 if (uploadWasFine
|| getFile().fileExists()) {
1041 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1043 cleanSecondFragment();
1046 // Force the preview if the file is an image
1047 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1048 startImagePreview(getFile());
1049 } // TODO what about other kind of previews?
1052 removeStickyBroadcast(intent
);
1060 * Class waiting for broadcast events from the {@link FielDownloader} service.
1062 * Updates the UI when a download is started or finished, provided that it is relevant for the
1065 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1067 public void onReceive(Context context
, Intent intent
) {
1068 boolean sameAccount
= isSameAccount(context
, intent
);
1069 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1070 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1072 if (sameAccount
&& isDescendant
) {
1073 refreshListOfFilesFragment();
1074 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1077 if (mWaitingToSend
!= null
) {
1078 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1079 if (mWaitingToSend
.isDown()) {
1080 sendDownloadedFile();
1084 removeStickyBroadcast(intent
);
1087 private boolean isDescendant(String downloadedRemotePath
) {
1088 OCFile currentDir
= getCurrentDir();
1089 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1092 private boolean isSameAccount(Context context
, Intent intent
) {
1093 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1094 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1099 public void browseToRoot() {
1100 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1101 if (listOfFiles
!= null
) { // should never be null, indeed
1102 while (mDirectories
.getCount() > 1) {
1105 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1106 listOfFiles
.listDirectory(root
);
1107 setFile(listOfFiles
.getCurrentFile());
1108 startSyncFolderOperation(root
);
1110 cleanSecondFragment();
1114 public void browseTo(OCFile folder
) {
1115 if (folder
== null
|| !folder
.isFolder()) {
1116 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1118 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1119 if (listOfFiles
!= null
) {
1120 setNavigationListWithFolder(folder
);
1121 listOfFiles
.listDirectory(folder
);
1122 setFile(listOfFiles
.getCurrentFile());
1123 startSyncFolderOperation(folder
);
1125 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1127 cleanSecondFragment();
1134 * Updates action bar and second fragment, if in dual pane mode.
1137 public void onBrowsedDownTo(OCFile directory
) {
1138 pushDirname(directory
);
1139 cleanSecondFragment();
1142 startSyncFolderOperation(directory
);
1147 * Shows the information of the {@link OCFile} received as a
1148 * parameter in the second fragment.
1150 * @param file {@link OCFile} whose details will be shown
1153 public void showDetails(OCFile file
) {
1154 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1155 setSecondFragment(detailFragment
);
1156 updateFragmentsVisibility(true
);
1157 updateNavigationElementsInActionBar(file
);
1165 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1166 ActionBar actionBar
= getSupportActionBar();
1167 if (chosenFile
== null
|| mDualPane
) {
1168 // only list of files - set for browsing through folders
1169 OCFile currentDir
= getCurrentDir();
1170 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1171 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1172 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1174 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1176 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1177 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1180 actionBar
.setDisplayHomeAsUpEnabled(true
);
1181 actionBar
.setDisplayShowTitleEnabled(true
);
1182 actionBar
.setTitle(chosenFile
.getFileName());
1183 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1189 protected ServiceConnection
newTransferenceServiceConnection() {
1190 return new ListServiceConnection();
1193 /** Defines callbacks for service binding, passed to bindService() */
1194 private class ListServiceConnection
implements ServiceConnection
{
1197 public void onServiceConnected(ComponentName component
, IBinder service
) {
1198 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1199 Log_OC
.d(TAG
, "Download service connected");
1200 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1201 if (mWaitingToPreview
!= null
)
1202 if (getStorageManager() != null
) {
1203 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1204 if (!mWaitingToPreview
.isDown()) {
1205 requestForDownload();
1209 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1210 Log_OC
.d(TAG
, "Upload service connected");
1211 mUploaderBinder
= (FileUploaderBinder
) service
;
1215 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1216 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1217 if (listOfFiles
!= null
) {
1218 listOfFiles
.listDirectory();
1220 FileFragment secondFragment
= getSecondFragment();
1221 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1222 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1223 detailFragment
.listenForTransferProgress();
1224 detailFragment
.updateFileDetails(false
, false
);
1229 public void onServiceDisconnected(ComponentName component
) {
1230 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1231 Log_OC
.d(TAG
, "Download service disconnected");
1232 mDownloaderBinder
= null
;
1233 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1234 Log_OC
.d(TAG
, "Upload service disconnected");
1235 mUploaderBinder
= null
;
1243 * Launch an intent to request the PIN code to the user before letting him use the app
1245 private void requestPinCode() {
1246 boolean pinStart
= false
;
1247 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1248 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1250 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1251 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1258 public void onSavedCertificate() {
1259 startSyncFolderOperation(getCurrentDir());
1264 public void onFailedSavingCertificate() {
1265 showDialog(DIALOG_CERT_NOT_SAVED
);
1269 public void onCancelCertificate() {
1274 * Updates the view associated to the activity after the finish of some operation over files
1275 * in the current account.
1277 * @param operation Removal operation performed.
1278 * @param result Result of the removal.
1281 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1282 super.onRemoteOperationFinish(operation
, result
);
1284 if (operation
instanceof RemoveFileOperation
) {
1285 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1287 } else if (operation
instanceof RenameFileOperation
) {
1288 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1290 } else if (operation
instanceof SynchronizeFileOperation
) {
1291 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1293 } else if (operation
instanceof CreateFolderOperation
) {
1294 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1296 } else if (operation
instanceof CreateShareOperation
) {
1297 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1299 } else if (operation
instanceof UnshareLinkOperation
) {
1300 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1307 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1308 if (result
.isSuccess()) {
1309 refreshShowDetails();
1310 refreshListOfFilesFragment();
1315 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1316 if (result
.isSuccess()) {
1317 refreshShowDetails();
1318 refreshListOfFilesFragment();
1320 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1321 cleanSecondFragment();
1322 refreshListOfFilesFragment();
1326 private void refreshShowDetails() {
1327 FileFragment details
= getSecondFragment();
1328 if (details
!= null
) {
1329 OCFile file
= details
.getFile();
1331 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1332 if (details
instanceof PreviewMediaFragment
) {
1333 // Refresh OCFile of the fragment
1334 ((PreviewMediaFragment
) details
).updateFile(file
);
1339 invalidateOptionsMenu();
1344 * Updates the view associated to the activity after the finish of an operation trying to remove a
1347 * @param operation Removal operation performed.
1348 * @param result Result of the removal.
1350 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1351 dismissLoadingDialog();
1353 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1357 if (result
.isSuccess()) {
1358 OCFile removedFile
= operation
.getFile();
1359 FileFragment second
= getSecondFragment();
1360 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1361 if (second
instanceof PreviewMediaFragment
) {
1362 ((PreviewMediaFragment
)second
).stopPreview(true
);
1364 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1365 cleanSecondFragment();
1367 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1368 refreshListOfFilesFragment();
1370 invalidateOptionsMenu();
1372 if (result
.isSslRecoverableException()) {
1373 mLastSslUntrustedServerResult
= result
;
1374 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1381 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1383 * @param operation Creation operation performed.
1384 * @param result Result of the creation.
1386 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1387 if (result
.isSuccess()) {
1388 dismissLoadingDialog();
1389 refreshListOfFilesFragment();
1391 dismissLoadingDialog();
1393 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1394 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1398 } catch (NotFoundException e
) {
1399 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1406 * Updates the view associated to the activity after the finish of an operation trying to rename a
1409 * @param operation Renaming operation performed.
1410 * @param result Result of the renaming.
1412 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1413 dismissLoadingDialog();
1414 OCFile renamedFile
= operation
.getFile();
1415 if (result
.isSuccess()) {
1416 FileFragment details
= getSecondFragment();
1417 if (details
!= null
) {
1418 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1419 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1420 showDetails(renamedFile
);
1422 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1423 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1424 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1425 int position
= ((PreviewMediaFragment
)details
).getPosition();
1426 startMediaPreview(renamedFile
, position
, true
);
1428 getFileOperationsHelper().openFile(renamedFile
);
1433 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1434 refreshListOfFilesFragment();
1438 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1442 if (result
.isSslRecoverableException()) {
1443 mLastSslUntrustedServerResult
= result
;
1444 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1449 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1450 dismissLoadingDialog();
1451 OCFile syncedFile
= operation
.getLocalFile();
1452 if (!result
.isSuccess()) {
1453 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1454 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1455 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1456 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1462 if (operation
.transferWasRequested()) {
1463 onTransferStateChanged(syncedFile
, true
, true
);
1466 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1478 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1479 refreshListOfFilesFragment();
1480 FileFragment details
= getSecondFragment();
1481 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1482 if (downloading
|| uploading
) {
1483 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1485 if (!file
.fileExists()) {
1486 cleanSecondFragment();
1488 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1496 private void requestForDownload() {
1497 Account account
= getAccount();
1498 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1499 Intent i
= new Intent(this, FileDownloader
.class);
1500 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1501 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1507 private OCFile
getCurrentDir() {
1508 OCFile file
= getFile();
1510 if (file
.isFolder()) {
1512 } else if (getStorageManager() != null
) {
1513 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1514 return getStorageManager().getFileByPath(parentPath
);
1520 public void startSyncFolderOperation(OCFile folder
) {
1521 long currentSyncTime
= System
.currentTimeMillis();
1523 mSyncInProgress
= true
;
1525 // perform folder synchronization
1526 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1529 getFileOperationsHelper().isSharedSupported(),
1530 getStorageManager(),
1532 getApplicationContext()
1534 synchFolderOp
.execute(getAccount(), this, null
, null
);
1536 setSupportProgressBarIndeterminateVisibility(true
);
1540 * Show untrusted cert dialog
1542 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1543 // Show a dialog with the certificate info
1544 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1545 FragmentManager fm
= getSupportFragmentManager();
1546 FragmentTransaction ft
= fm
.beginTransaction();
1547 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1550 private void requestForDownload(OCFile file
) {
1551 Account account
= getAccount();
1552 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1553 Intent i
= new Intent(this, FileDownloader
.class);
1554 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1555 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1560 private void sendDownloadedFile(){
1561 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1562 mWaitingToSend
= null
;
1567 * Requests the download of the received {@link OCFile} , updates the UI
1568 * to monitor the download progress and prepares the activity to send the file
1569 * when the download finishes.
1571 * @param file {@link OCFile} to download and preview.
1573 public void startDownloadForSending(OCFile file
) {
1574 mWaitingToSend
= file
;
1575 requestForDownload(mWaitingToSend
);
1576 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1577 updateFragmentsVisibility(hasSecondFragment
);
1581 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1583 * @param file Image {@link OCFile} to show.
1585 public void startImagePreview(OCFile file
) {
1586 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1587 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1588 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1589 startActivity(showDetailsIntent
);
1594 * Stars the preview of an already down media {@link OCFile}.
1596 * @param file Media {@link OCFile} to preview.
1597 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1598 * @param autoplay When 'true', the playback will start without user interactions.
1600 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1601 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1602 setSecondFragment(mediaFragment
);
1603 updateFragmentsVisibility(true
);
1604 updateNavigationElementsInActionBar(file
);
1609 * Requests the download of the received {@link OCFile} , updates the UI
1610 * to monitor the download progress and prepares the activity to preview
1611 * or open the file when the download finishes.
1613 * @param file {@link OCFile} to download and preview.
1615 public void startDownloadForPreview(OCFile file
) {
1616 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1617 setSecondFragment(detailFragment
);
1618 mWaitingToPreview
= file
;
1619 requestForDownload();
1620 updateFragmentsVisibility(true
);
1621 updateNavigationElementsInActionBar(file
);
1626 public void cancelTransference(OCFile file
) {
1627 getFileOperationsHelper().cancelTransference(file
);
1628 if (mWaitingToPreview
!= null
&&
1629 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1630 mWaitingToPreview
= null
;
1632 if (mWaitingToSend
!= null
&&
1633 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1634 mWaitingToSend
= null
;
1636 onTransferStateChanged(file
, false
, false
);