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 org
.apache
.commons
.httpclient
.methods
.PostMethod
;
26 import android
.accounts
.Account
;
27 import android
.accounts
.AccountManager
;
28 import android
.accounts
.AuthenticatorException
;
29 import android
.accounts
.OperationCanceledException
;
30 import android
.app
.AlertDialog
;
31 import android
.app
.Dialog
;
32 import android
.app
.ProgressDialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ComponentName
;
35 import android
.content
.ContentResolver
;
36 import android
.content
.Context
;
37 import android
.content
.DialogInterface
;
38 import android
.content
.Intent
;
39 import android
.content
.IntentFilter
;
40 import android
.content
.ServiceConnection
;
41 import android
.content
.SharedPreferences
;
42 import android
.content
.SyncRequest
;
43 import android
.content
.res
.Resources
.NotFoundException
;
44 import android
.database
.Cursor
;
45 import android
.net
.Uri
;
46 import android
.os
.Bundle
;
47 import android
.os
.IBinder
;
48 import android
.preference
.PreferenceManager
;
49 import android
.provider
.MediaStore
;
50 import android
.support
.v4
.app
.Fragment
;
51 import android
.support
.v4
.app
.FragmentManager
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.support
.v4
.widget
.SwipeRefreshLayout
;
54 import android
.util
.Log
;
55 import android
.view
.View
;
56 import android
.view
.ViewGroup
;
57 import android
.widget
.ArrayAdapter
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.ActionBar
;
62 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
63 import com
.actionbarsherlock
.view
.Menu
;
64 import com
.actionbarsherlock
.view
.MenuInflater
;
65 import com
.actionbarsherlock
.view
.MenuItem
;
66 import com
.actionbarsherlock
.view
.Window
;
67 import com
.owncloud
.android
.BuildConfig
;
68 import com
.owncloud
.android
.MainApp
;
69 import com
.owncloud
.android
.R
;
70 import com
.owncloud
.android
.datamodel
.OCFile
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
;
72 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
;
74 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
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
.lib
.common
.utils
.Log_OC
;
85 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
86 import com
.owncloud
.android
.operations
.CreateShareOperation
;
87 import com
.owncloud
.android
.operations
.MoveFileOperation
;
88 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
89 import com
.owncloud
.android
.operations
.RenameFileOperation
;
90 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
91 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
92 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
93 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
94 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
95 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
96 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
97 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
98 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
100 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
105 import com
.owncloud
.android
.utils
.DisplayUtils
;
106 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
110 * Displays, what files the user has available in his ownCloud.
112 * @author Bartek Przybylski
113 * @author David A. Velasco
116 public class FileDisplayActivity
extends HookActivity
implements
117 FileFragment
.ContainerActivity
, OnNavigationListener
,
118 OnSslUntrustedCertListener
, SwipeRefreshLayout
.OnRefreshListener
{
120 private ArrayAdapter
<String
> mDirectories
;
122 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
123 private UploadFinishReceiver mUploadFinishReceiver
;
124 private DownloadFinishReceiver mDownloadFinishReceiver
;
125 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
127 private boolean mDualPane
;
128 private View mLeftFragmentContainer
;
129 private View mRightFragmentContainer
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final int DIALOG_SHORT_WAIT
= 0;
136 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
137 private static final int DIALOG_CERT_NOT_SAVED
= 2;
139 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
141 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
142 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
143 public static final int ACTION_MOVE_FILES
= 3;
145 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
147 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
148 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
150 private OCFile mWaitingToPreview
;
152 private boolean mSyncInProgress
= false
;
154 private String DIALOG_UNTRUSTED_CERT
;
156 private OCFile mWaitingToSend
;
159 protected void onCreate(Bundle savedInstanceState
) {
160 Log_OC
.d(TAG
, "onCreate() start");
161 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
163 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
165 // PIN CODE request ; best location is to decide, let's try this first
166 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
168 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
172 /// grant that FileObserverService is watching favourite files
173 if (savedInstanceState
== null
) {
174 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
175 startService(initObserversIntent
);
178 /// Load of saved instance state
179 if(savedInstanceState
!= null
) {
180 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
181 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
182 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
185 mWaitingToPreview
= null
;
186 mSyncInProgress
= false
;
187 mWaitingToSend
= null
;
192 // Inflate and set the layout view
193 setContentView(R
.layout
.files
);
194 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
195 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
196 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
197 if (savedInstanceState
== null
) {
198 createMinFragments();
202 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
203 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
204 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
208 Log_OC
.d(TAG
, "onCreate() end");
212 protected void onStart() {
214 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
218 protected void onDestroy() {
223 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
226 protected void onAccountSet(boolean stateWasRecovered
) {
227 super.onAccountSet(stateWasRecovered
);
228 if (getAccount() != null
) {
229 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
230 OCFile file
= getFile();
231 // get parent from path
232 String parentPath
= "";
234 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
235 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
236 // get parent from path
237 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
238 if (getStorageManager().getFileByPath(parentPath
) == null
)
239 file
= null
; // not able to know the directory where the file is uploading
241 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
245 // fall back to root folder
246 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
249 setNavigationListWithFolder(file
);
251 if (!stateWasRecovered
) {
252 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
253 initFragmentsWithFile();
254 if (file
.isFolder()) {
255 startSyncFolderOperation(file
);
259 updateFragmentsVisibility(!file
.isFolder());
260 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
266 private void setNavigationListWithFolder(OCFile file
) {
267 mDirectories
.clear();
268 OCFile fileIt
= file
;
270 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
271 if (fileIt
.isFolder()) {
272 mDirectories
.add(fileIt
.getFileName());
274 // get parent from path
275 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
276 fileIt
= getStorageManager().getFileByPath(parentPath
);
278 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
282 private void createMinFragments() {
283 OCFileListFragment listOfFiles
= new OCFileListFragment();
284 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
285 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
286 transaction
.commit();
289 private void initFragmentsWithFile() {
290 if (getAccount() != null
&& getFile() != null
) {
292 OCFileListFragment listOfFiles
= getListOfFilesFragment();
293 if (listOfFiles
!= null
) {
294 listOfFiles
.listDirectory(getCurrentDir());
296 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
300 OCFile file
= getFile();
301 Fragment secondFragment
= chooseInitialSecondFragment(file
);
302 if (secondFragment
!= null
) {
303 setSecondFragment(secondFragment
);
304 updateFragmentsVisibility(true
);
305 updateNavigationElementsInActionBar(file
);
308 cleanSecondFragment();
312 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
313 if (getAccount() == null
) {
314 Log_OC
.wtf(TAG
, "\t account is NULL");
316 if (getFile() == null
) {
317 Log_OC
.wtf(TAG
, "\t file is NULL");
322 private Fragment
chooseInitialSecondFragment(OCFile file
) {
323 Fragment secondFragment
= null
;
324 if (file
!= null
&& !file
.isFolder()) {
325 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
326 && file
.getLastSyncDateForProperties() > 0 // temporal fix
328 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
329 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
330 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
333 secondFragment
= new FileDetailFragment(file
, getAccount());
336 return secondFragment
;
341 * Replaces the second fragment managed by the activity with the received as
344 * Assumes never will be more than two fragments managed at the same time.
346 * @param fragment New second Fragment to set.
348 private void setSecondFragment(Fragment fragment
) {
349 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
350 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
351 transaction
.commit();
355 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
357 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
360 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
361 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
364 } else if (existsSecondFragment
) {
365 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
366 mLeftFragmentContainer
.setVisibility(View
.GONE
);
368 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
376 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
377 mRightFragmentContainer
.setVisibility(View
.GONE
);
383 private OCFileListFragment
getListOfFilesFragment() {
384 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
385 if (listOfFiles
!= null
) {
386 return (OCFileListFragment
)listOfFiles
;
388 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
392 public FileFragment
getSecondFragment() {
393 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
394 if (second
!= null
) {
395 return (FileFragment
)second
;
400 protected void cleanSecondFragment() {
401 Fragment second
= getSecondFragment();
402 if (second
!= null
) {
403 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
407 updateFragmentsVisibility(false
);
408 updateNavigationElementsInActionBar(null
);
411 protected void refreshListOfFilesFragment() {
412 OCFileListFragment fileListFragment
= getListOfFilesFragment();
413 if (fileListFragment
!= null
) {
414 fileListFragment
.listDirectory();
418 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
419 FileFragment secondFragment
= getSecondFragment();
420 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
421 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
422 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
423 OCFile fileInFragment
= detailsFragment
.getFile();
424 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
425 // the user browsed to other file ; forget the automatic preview
426 mWaitingToPreview
= null
;
428 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
429 // grant that the right panel updates the progress bar
430 detailsFragment
.listenForTransferProgress();
431 detailsFragment
.updateFileDetails(true
, false
);
433 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
434 // update the right panel
435 boolean detailsFragmentChanged
= false
;
438 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
439 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
440 startMediaPreview(mWaitingToPreview
, 0, true
);
441 detailsFragmentChanged
= true
;
443 getFileOperationsHelper().openFile(mWaitingToPreview
);
446 mWaitingToPreview
= null
;
448 if (!detailsFragmentChanged
) {
449 detailsFragment
.updateFileDetails(false
, (success
));
456 public boolean onPrepareOptionsMenu(Menu menu
) {
457 if (BuildConfig
.DEBUG
) {
458 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
460 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
462 return super.onPrepareOptionsMenu(menu
);
466 public boolean onCreateOptionsMenu(Menu menu
) {
467 MenuInflater inflater
= getSherlock().getMenuInflater();
468 inflater
.inflate(R
.menu
.main_menu
, menu
);
473 public boolean onOptionsItemSelected(MenuItem item
) {
474 boolean retval
= true
;
475 switch (item
.getItemId()) {
476 case R
.id
.action_create_dir
: {
477 CreateFolderDialogFragment dialog
=
478 CreateFolderDialogFragment
.newInstance(getCurrentDir());
479 dialog
.show(getSupportFragmentManager(), "createdirdialog");
482 case R
.id
.action_sync_account
: {
483 startSynchronization();
486 case R
.id
.action_upload
: {
487 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
490 case R
.id
.action_settings
: {
491 Intent settingsIntent
= new Intent(this, Preferences
.class);
492 startActivity(settingsIntent
);
495 case R
.id
.action_logger
: {
496 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
497 startActivity(loggerIntent
);
500 case android
.R
.id
.home
: {
501 FileFragment second
= getSecondFragment();
502 OCFile currentDir
= getCurrentDir();
503 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
504 (second
!= null
&& second
.getFile() != null
)) {
511 retval
= super.onOptionsItemSelected(item
);
516 private void startSynchronization() {
517 Log_OC
.e(TAG
, "Got to start sync");
518 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
519 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
520 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
521 Bundle bundle
= new Bundle();
522 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
523 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
524 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
525 ContentResolver
.requestSync(
527 MainApp
.getAuthority(), bundle
);
529 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
530 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
531 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
532 builder
.setExpedited(true
);
533 builder
.setManual(true
);
535 SyncRequest request
= builder
.build();
536 ContentResolver
.requestSync(request
);
542 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
543 if (itemPosition
!= 0) {
544 String targetPath
= "";
545 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
546 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
548 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
549 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
550 if (targetFolder
!= null
) {
551 browseTo(targetFolder
);
554 // the next operation triggers a new call to this method, but it's necessary to
555 // ensure that the name exposed in the action bar is the current directory when the
556 // user selected it in the navigation list
557 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
558 getSupportActionBar().setSelectedNavigationItem(0);
564 * Called, when the user selected something for uploading
566 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
567 super.onActivityResult(requestCode
, resultCode
, data
);
569 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
570 requestSimpleUpload(data
, resultCode
);
572 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
573 requestMultipleUpload(data
, resultCode
);
575 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
576 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
578 final Intent fData
= data
;
579 final int fResultCode
= resultCode
;
580 getHandler().postDelayed(
584 requestMoveOperation(fData
, fResultCode
);
587 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
592 private void requestMultipleUpload(Intent data
, int resultCode
) {
593 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
594 if (filePaths
!= null
) {
595 String
[] remotePaths
= new String
[filePaths
.length
];
596 String remotePathBase
= "";
597 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
598 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
600 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
601 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
602 for (int j
= 0; j
< remotePaths
.length
; j
++) {
603 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
606 Intent i
= new Intent(this, FileUploader
.class);
607 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
608 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
609 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
610 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
611 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
612 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
616 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
617 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
624 private void requestSimpleUpload(Intent data
, int resultCode
) {
625 String filepath
= null
;
627 Uri selectedImageUri
= data
.getData();
629 String filemanagerstring
= selectedImageUri
.getPath();
630 String selectedImagePath
= getPath(selectedImageUri
);
632 if (selectedImagePath
!= null
)
633 filepath
= selectedImagePath
;
635 filepath
= filemanagerstring
;
637 } catch (Exception e
) {
638 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
642 if (filepath
== null
) {
643 Log_OC
.e(TAG
, "Couldnt resolve path to file");
644 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
650 Intent i
= new Intent(this, FileUploader
.class);
651 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
653 String remotepath
= new String();
654 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
655 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
657 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
658 remotepath
+= OCFile
.PATH_SEPARATOR
;
659 remotepath
+= new File(filepath
).getName();
661 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
662 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
663 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
664 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
665 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
670 * Request the operation for moving the file/folder from one path to another
672 * @param data Intent received
673 * @param resultCode Result code received
675 private void requestMoveOperation(Intent data
, int resultCode
) {
676 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
677 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
678 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
682 public void onBackPressed() {
683 OCFileListFragment listOfFiles
= getListOfFilesFragment();
684 if (mDualPane
|| getSecondFragment() == null
) {
685 if (listOfFiles
!= null
) { // should never be null, indeed
686 if (mDirectories
.getCount() <= 1) {
690 int levelsUp
= listOfFiles
.onBrowseUp();
691 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
696 if (listOfFiles
!= null
) { // should never be null, indeed
697 setFile(listOfFiles
.getCurrentFile());
699 cleanSecondFragment();
704 protected void onSaveInstanceState(Bundle outState
) {
705 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
706 Log_OC
.e(TAG
, "onSaveInstanceState() start");
707 super.onSaveInstanceState(outState
);
708 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
709 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
710 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
711 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
713 Log_OC
.d(TAG
, "onSaveInstanceState() end");
719 protected void onResume() {
721 Log_OC
.e(TAG
, "onResume() start");
723 // refresh list of files
724 refreshListOfFilesFragment();
726 // Listen for sync messages
727 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
728 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
729 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
730 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
731 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
732 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
733 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
734 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
736 // Listen for upload messages
737 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
738 mUploadFinishReceiver
= new UploadFinishReceiver();
739 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
741 // Listen for download messages
742 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
743 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
744 mDownloadFinishReceiver
= new DownloadFinishReceiver();
745 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
747 Log_OC
.d(TAG
, "onResume() end");
752 protected void onPause() {
753 Log_OC
.e(TAG
, "onPause() start");
754 if (mSyncBroadcastReceiver
!= null
) {
755 unregisterReceiver(mSyncBroadcastReceiver
);
756 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
757 mSyncBroadcastReceiver
= null
;
759 if (mUploadFinishReceiver
!= null
) {
760 unregisterReceiver(mUploadFinishReceiver
);
761 mUploadFinishReceiver
= null
;
763 if (mDownloadFinishReceiver
!= null
) {
764 unregisterReceiver(mDownloadFinishReceiver
);
765 mDownloadFinishReceiver
= null
;
769 Log_OC
.d(TAG
, "onPause() end");
775 protected Dialog
onCreateDialog(int id
) {
776 Dialog dialog
= null
;
777 AlertDialog
.Builder builder
;
779 case DIALOG_SHORT_WAIT
: {
780 ProgressDialog working_dialog
= new ProgressDialog(this);
781 working_dialog
.setMessage(getResources().getString(
782 R
.string
.wait_a_moment
));
783 working_dialog
.setIndeterminate(true
);
784 working_dialog
.setCancelable(false
);
785 dialog
= working_dialog
;
788 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
791 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
792 getString(R
.string
.actionbar_upload_from_apps
) };
794 builder
= new AlertDialog
.Builder(this);
795 builder
.setTitle(R
.string
.actionbar_upload
);
796 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
797 public void onClick(DialogInterface dialog
, int item
) {
800 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
801 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
802 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
804 // TODO create and handle new fragment
805 // LocalFileListFragment
807 } else if (item
== 1) {
808 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
809 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
810 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
811 ACTION_SELECT_CONTENT_FROM_APPS
);
815 dialog
= builder
.create();
818 case DIALOG_CERT_NOT_SAVED
: {
819 builder
= new AlertDialog
.Builder(this);
820 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
821 builder
.setCancelable(false
);
822 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
824 public void onClick(DialogInterface dialog
, int which
) {
828 dialog
= builder
.create();
840 * Translates a content URI of an image to a physical path
842 * @param uri The URI to resolve
843 * @return The path to the image or null if it could not be found
845 public String
getPath(Uri uri
) {
846 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
847 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
848 if (cursor
!= null
) {
849 int column_index
= cursor
850 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
851 cursor
.moveToFirst();
852 return cursor
.getString(column_index
);
858 * Pushes a directory to the drop down list
859 * @param directory to push
860 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
862 public void pushDirname(OCFile directory
) {
863 if(!directory
.isFolder()){
864 throw new IllegalArgumentException("Only directories may be pushed!");
866 mDirectories
.insert(directory
.getFileName(), 0);
871 * Pops a directory name from the drop down list
872 * @return True, unless the stack is empty
874 public boolean popDirname() {
875 mDirectories
.remove(mDirectories
.getItem(0));
876 return !mDirectories
.isEmpty();
879 // Custom array adapter to override text colors
880 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
882 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
886 public View
getView(int position
, View convertView
, ViewGroup parent
) {
887 View v
= super.getView(position
, convertView
, parent
);
889 ((TextView
) v
).setTextColor(getResources().getColorStateList(
890 android
.R
.color
.white
));
892 fixRoot((TextView
) v
);
896 public View
getDropDownView(int position
, View convertView
,
898 View v
= super.getDropDownView(position
, convertView
, parent
);
900 ((TextView
) v
).setTextColor(getResources().getColorStateList(
901 android
.R
.color
.white
));
903 fixRoot((TextView
) v
);
907 private void fixRoot(TextView v
) {
908 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
909 v
.setText(R
.string
.default_display_name_for_root_folder
);
915 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
918 * {@link BroadcastReceiver} to enable syncing feedback in UI
921 public void onReceive(Context context
, Intent intent
) {
923 String event
= intent
.getAction();
924 Log_OC
.d(TAG
, "Received broadcast " + event
);
925 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
926 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
927 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
928 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
932 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
933 mSyncInProgress
= true
;
936 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
937 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
939 if (currentDir
== null
) {
940 // current folder was removed from the server
941 Toast
.makeText( FileDisplayActivity
.this,
942 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
948 if (currentFile
== null
&& !getFile().isFolder()) {
949 // currently selected file was removed in the server, and now we know it
950 cleanSecondFragment();
951 currentFile
= currentDir
;
954 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
955 OCFileListFragment fileListFragment
= getListOfFilesFragment();
956 if (fileListFragment
!= null
) {
957 fileListFragment
.listDirectory(currentDir
);
960 setFile(currentFile
);
963 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
965 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
967 /// TODO refactor and make common
968 synchResult
!= null
&& !synchResult
.isSuccess() &&
969 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
970 synchResult
.isIdPRedirection() ||
971 (synchResult
.isException() && synchResult
.getException()
972 instanceof AuthenticatorException
))) {
974 OwnCloudClient client
= null
;
976 OwnCloudAccount ocAccount
=
977 new OwnCloudAccount(getAccount(), context
);
978 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
979 removeClientFor(ocAccount
));
980 // TODO get rid of these exceptions
981 } catch (AccountNotFoundException e
) {
983 } catch (AuthenticatorException e
) {
985 } catch (OperationCanceledException e
) {
987 } catch (IOException e
) {
991 if (client
!= null
) {
992 OwnCloudCredentials cred
= client
.getCredentials();
994 AccountManager am
= AccountManager
.get(context
);
995 if (cred
.authTokenExpires()) {
996 am
.invalidateAuthToken(
1001 am
.clearPassword(getAccount());
1006 requestCredentialsUpdate();
1010 removeStickyBroadcast(intent
);
1011 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1012 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1014 setBackgroundText();
1018 if (synchResult
!= null
) {
1019 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1020 mLastSslUntrustedServerResult
= synchResult
;
1023 } catch (RuntimeException e
) {
1024 // avoid app crashes after changing the serial id of RemoteOperationResult
1025 // in owncloud library with broadcast notifications pending to process
1026 removeStickyBroadcast(intent
);
1032 * Show a text message on screen view for notifying user if content is
1033 * loading or folder is empty
1035 private void setBackgroundText() {
1036 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1037 if (ocFileListFragment
!= null
) {
1038 int message
= R
.string
.file_list_loading
;
1039 if (!mSyncInProgress
) {
1040 // In case file list is empty
1041 message
= R
.string
.file_list_empty
;
1043 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1045 Log_OC
.e(TAG
, "OCFileListFragment is null");
1050 * Once the file upload has finished -> update view
1052 private class UploadFinishReceiver
extends BroadcastReceiver
{
1054 * Once the file upload has finished -> update view
1055 * @author David A. Velasco
1056 * {@link BroadcastReceiver} to enable upload feedback in UI
1059 public void onReceive(Context context
, Intent intent
) {
1061 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1062 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1063 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1064 OCFile currentDir
= getCurrentDir();
1065 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1066 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1068 if (sameAccount
&& isDescendant
) {
1069 refreshListOfFilesFragment();
1072 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1073 boolean renamedInUpload
= getFile().getRemotePath().
1074 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1075 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1077 FileFragment details
= getSecondFragment();
1078 boolean detailFragmentIsShown
= (details
!= null
&&
1079 details
instanceof FileDetailFragment
);
1081 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1082 if (uploadWasFine
) {
1083 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1085 if (renamedInUpload
) {
1086 String newName
= (new File(uploadedRemotePath
)).getName();
1087 Toast msg
= Toast
.makeText(
1090 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1095 if (uploadWasFine
|| getFile().fileExists()) {
1096 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1098 cleanSecondFragment();
1101 // Force the preview if the file is an image
1102 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1103 startImagePreview(getFile());
1104 } // TODO what about other kind of previews?
1108 if (intent
!= null
) {
1109 removeStickyBroadcast(intent
);
1119 * Class waiting for broadcast events from the {@link FielDownloader} service.
1121 * Updates the UI when a download is started or finished, provided that it is relevant for the
1124 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1126 public void onReceive(Context context
, Intent intent
) {
1128 boolean sameAccount
= isSameAccount(context
, intent
);
1129 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1130 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1132 if (sameAccount
&& isDescendant
) {
1133 refreshListOfFilesFragment();
1134 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1137 if (mWaitingToSend
!= null
) {
1138 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1139 if (mWaitingToSend
.isDown()) {
1140 sendDownloadedFile();
1145 if (intent
!= null
) {
1146 removeStickyBroadcast(intent
);
1151 private boolean isDescendant(String downloadedRemotePath
) {
1152 OCFile currentDir
= getCurrentDir();
1153 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1156 private boolean isSameAccount(Context context
, Intent intent
) {
1157 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1158 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1163 public void browseToRoot() {
1164 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1165 if (listOfFiles
!= null
) { // should never be null, indeed
1166 while (mDirectories
.getCount() > 1) {
1169 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1170 listOfFiles
.listDirectory(root
);
1171 setFile(listOfFiles
.getCurrentFile());
1172 startSyncFolderOperation(root
);
1174 cleanSecondFragment();
1178 public void browseTo(OCFile folder
) {
1179 if (folder
== null
|| !folder
.isFolder()) {
1180 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1182 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1183 if (listOfFiles
!= null
) {
1184 setNavigationListWithFolder(folder
);
1185 listOfFiles
.listDirectory(folder
);
1186 setFile(listOfFiles
.getCurrentFile());
1187 startSyncFolderOperation(folder
);
1189 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1191 cleanSecondFragment();
1198 * Updates action bar and second fragment, if in dual pane mode.
1201 public void onBrowsedDownTo(OCFile directory
) {
1202 pushDirname(directory
);
1203 cleanSecondFragment();
1206 startSyncFolderOperation(directory
);
1211 * Shows the information of the {@link OCFile} received as a
1212 * parameter in the second fragment.
1214 * @param file {@link OCFile} whose details will be shown
1217 public void showDetails(OCFile file
) {
1218 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1219 setSecondFragment(detailFragment
);
1220 updateFragmentsVisibility(true
);
1221 updateNavigationElementsInActionBar(file
);
1229 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1230 ActionBar actionBar
= getSupportActionBar();
1231 if (chosenFile
== null
|| mDualPane
) {
1232 // only list of files - set for browsing through folders
1233 OCFile currentDir
= getCurrentDir();
1234 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1235 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1236 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1238 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1240 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1241 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1244 actionBar
.setDisplayHomeAsUpEnabled(true
);
1245 actionBar
.setDisplayShowTitleEnabled(true
);
1246 actionBar
.setTitle(chosenFile
.getFileName());
1247 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1253 protected ServiceConnection
newTransferenceServiceConnection() {
1254 return new ListServiceConnection();
1257 /** Defines callbacks for service binding, passed to bindService() */
1258 private class ListServiceConnection
implements ServiceConnection
{
1261 public void onServiceConnected(ComponentName component
, IBinder service
) {
1262 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1263 Log_OC
.d(TAG
, "Download service connected");
1264 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1265 if (mWaitingToPreview
!= null
)
1266 if (getStorageManager() != null
) {
1267 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1268 if (!mWaitingToPreview
.isDown()) {
1269 requestForDownload();
1273 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1274 Log_OC
.d(TAG
, "Upload service connected");
1275 mUploaderBinder
= (FileUploaderBinder
) service
;
1279 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1280 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1281 if (listOfFiles
!= null
) {
1282 listOfFiles
.listDirectory();
1284 FileFragment secondFragment
= getSecondFragment();
1285 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1286 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1287 detailFragment
.listenForTransferProgress();
1288 detailFragment
.updateFileDetails(false
, false
);
1293 public void onServiceDisconnected(ComponentName component
) {
1294 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1295 Log_OC
.d(TAG
, "Download service disconnected");
1296 mDownloaderBinder
= null
;
1297 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1298 Log_OC
.d(TAG
, "Upload service disconnected");
1299 mUploaderBinder
= null
;
1307 * Launch an intent to request the PIN code to the user before letting him use the app
1309 private void requestPinCode() {
1310 boolean pinStart
= false
;
1311 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1312 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1314 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1315 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1322 public void onSavedCertificate() {
1323 startSyncFolderOperation(getCurrentDir());
1328 public void onFailedSavingCertificate() {
1329 showDialog(DIALOG_CERT_NOT_SAVED
);
1333 public void onCancelCertificate() {
1338 * Updates the view associated to the activity after the finish of some operation over files
1339 * in the current account.
1341 * @param operation Removal operation performed.
1342 * @param result Result of the removal.
1345 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1346 super.onRemoteOperationFinish(operation
, result
);
1348 if (operation
instanceof RemoveFileOperation
) {
1349 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1351 } else if (operation
instanceof RenameFileOperation
) {
1352 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1354 } else if (operation
instanceof SynchronizeFileOperation
) {
1355 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1357 } else if (operation
instanceof CreateFolderOperation
) {
1358 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1360 } else if (operation
instanceof CreateShareOperation
) {
1361 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1363 } else if (operation
instanceof UnshareLinkOperation
) {
1364 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1366 } else if (operation
instanceof MoveFileOperation
) {
1367 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1373 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1374 if (result
.isSuccess()) {
1375 refreshShowDetails();
1376 refreshListOfFilesFragment();
1381 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1382 if (result
.isSuccess()) {
1383 refreshShowDetails();
1384 refreshListOfFilesFragment();
1386 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1387 cleanSecondFragment();
1388 refreshListOfFilesFragment();
1392 private void refreshShowDetails() {
1393 FileFragment details
= getSecondFragment();
1394 if (details
!= null
) {
1395 OCFile file
= details
.getFile();
1397 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1398 if (details
instanceof PreviewMediaFragment
) {
1399 // Refresh OCFile of the fragment
1400 ((PreviewMediaFragment
) details
).updateFile(file
);
1405 invalidateOptionsMenu();
1410 * Updates the view associated to the activity after the finish of an operation trying to remove a
1413 * @param operation Removal operation performed.
1414 * @param result Result of the removal.
1416 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1417 dismissLoadingDialog();
1419 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1423 if (result
.isSuccess()) {
1424 OCFile removedFile
= operation
.getFile();
1425 FileFragment second
= getSecondFragment();
1426 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1427 if (second
instanceof PreviewMediaFragment
) {
1428 ((PreviewMediaFragment
)second
).stopPreview(true
);
1430 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1431 cleanSecondFragment();
1433 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1434 refreshListOfFilesFragment();
1436 invalidateOptionsMenu();
1438 if (result
.isSslRecoverableException()) {
1439 mLastSslUntrustedServerResult
= result
;
1440 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1447 * Updates the view associated to the activity after the finish of an operation trying to move a
1450 * @param operation Move operation performed.
1451 * @param result Result of the move operation.
1453 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1454 if (result
.isSuccess()) {
1455 dismissLoadingDialog();
1456 refreshListOfFilesFragment();
1458 dismissLoadingDialog();
1460 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1461 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1465 } catch (NotFoundException e
) {
1466 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1473 * Updates the view associated to the activity after the finish of an operation trying to rename a
1476 * @param operation Renaming operation performed.
1477 * @param result Result of the renaming.
1479 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1480 dismissLoadingDialog();
1481 OCFile renamedFile
= operation
.getFile();
1482 if (result
.isSuccess()) {
1483 FileFragment details
= getSecondFragment();
1484 if (details
!= null
) {
1485 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1486 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1487 showDetails(renamedFile
);
1489 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1490 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1491 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1492 int position
= ((PreviewMediaFragment
)details
).getPosition();
1493 startMediaPreview(renamedFile
, position
, true
);
1495 getFileOperationsHelper().openFile(renamedFile
);
1500 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1501 refreshListOfFilesFragment();
1505 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1509 if (result
.isSslRecoverableException()) {
1510 mLastSslUntrustedServerResult
= result
;
1511 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1516 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1517 dismissLoadingDialog();
1518 OCFile syncedFile
= operation
.getLocalFile();
1519 if (!result
.isSuccess()) {
1520 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1521 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1522 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1523 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1529 if (operation
.transferWasRequested()) {
1530 onTransferStateChanged(syncedFile
, true
, true
);
1533 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1541 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1543 * @param operation Creation operation performed.
1544 * @param result Result of the creation.
1546 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1547 if (result
.isSuccess()) {
1548 dismissLoadingDialog();
1549 refreshListOfFilesFragment();
1551 dismissLoadingDialog();
1553 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1554 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1558 } catch (NotFoundException e
) {
1559 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1569 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1570 refreshListOfFilesFragment();
1571 FileFragment details
= getSecondFragment();
1572 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1573 if (downloading
|| uploading
) {
1574 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1576 if (!file
.fileExists()) {
1577 cleanSecondFragment();
1579 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1587 private void requestForDownload() {
1588 Account account
= getAccount();
1589 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1590 Intent i
= new Intent(this, FileDownloader
.class);
1591 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1592 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1598 private OCFile
getCurrentDir() {
1599 OCFile file
= getFile();
1601 if (file
.isFolder()) {
1603 } else if (getStorageManager() != null
) {
1604 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1605 return getStorageManager().getFileByPath(parentPath
);
1611 public void startSyncFolderOperation(OCFile folder
) {
1612 long currentSyncTime
= System
.currentTimeMillis();
1614 mSyncInProgress
= true
;
1616 // perform folder synchronization
1617 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1620 getFileOperationsHelper().isSharedSupported(),
1621 getStorageManager(),
1623 getApplicationContext()
1625 synchFolderOp
.execute(getAccount(), this, null
, null
);
1627 setSupportProgressBarIndeterminateVisibility(true
);
1629 setBackgroundText();
1633 * Show untrusted cert dialog
1635 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1636 // Show a dialog with the certificate info
1637 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1638 FragmentManager fm
= getSupportFragmentManager();
1639 FragmentTransaction ft
= fm
.beginTransaction();
1640 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1643 private void requestForDownload(OCFile file
) {
1644 Account account
= getAccount();
1645 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1646 Intent i
= new Intent(this, FileDownloader
.class);
1647 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1648 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1653 private void sendDownloadedFile(){
1654 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1655 mWaitingToSend
= null
;
1660 * Requests the download of the received {@link OCFile} , updates the UI
1661 * to monitor the download progress and prepares the activity to send the file
1662 * when the download finishes.
1664 * @param file {@link OCFile} to download and preview.
1666 public void startDownloadForSending(OCFile file
) {
1667 mWaitingToSend
= file
;
1668 requestForDownload(mWaitingToSend
);
1669 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1670 updateFragmentsVisibility(hasSecondFragment
);
1674 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1676 * @param file Image {@link OCFile} to show.
1678 public void startImagePreview(OCFile file
) {
1679 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1680 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1681 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1682 startActivity(showDetailsIntent
);
1687 * Stars the preview of an already down media {@link OCFile}.
1689 * @param file Media {@link OCFile} to preview.
1690 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1691 * @param autoplay When 'true', the playback will start without user interactions.
1693 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1694 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1695 setSecondFragment(mediaFragment
);
1696 updateFragmentsVisibility(true
);
1697 updateNavigationElementsInActionBar(file
);
1702 * Requests the download of the received {@link OCFile} , updates the UI
1703 * to monitor the download progress and prepares the activity to preview
1704 * or open the file when the download finishes.
1706 * @param file {@link OCFile} to download and preview.
1708 public void startDownloadForPreview(OCFile file
) {
1709 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1710 setSecondFragment(detailFragment
);
1711 mWaitingToPreview
= file
;
1712 requestForDownload();
1713 updateFragmentsVisibility(true
);
1714 updateNavigationElementsInActionBar(file
);
1719 public void cancelTransference(OCFile file
) {
1720 getFileOperationsHelper().cancelTransference(file
);
1721 if (mWaitingToPreview
!= null
&&
1722 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1723 mWaitingToPreview
= null
;
1725 if (mWaitingToSend
!= null
&&
1726 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1727 mWaitingToSend
= null
;
1729 onTransferStateChanged(file
, false
, false
);
1733 public void onRefresh() {
1734 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1735 if (listOfFiles
!= null
) {
1736 OCFile folder
= listOfFiles
.getCurrentFile();
1737 if (folder
!= null
) {
1738 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1739 listDirectory(mFile);*/
1740 startSyncFolderOperation(folder
);