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
.widget
.SwipeRefreshLayout
;
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
.FileDownloader
.FileDownloaderBinder
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
76 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
77 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.MoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
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
,
115 OnSslUntrustedCertListener
, SwipeRefreshLayout
.OnRefreshListener
{
117 private ArrayAdapter
<String
> mDirectories
;
119 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
120 private UploadFinishReceiver mUploadFinishReceiver
;
121 private DownloadFinishReceiver mDownloadFinishReceiver
;
122 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
124 private boolean mDualPane
;
125 private View mLeftFragmentContainer
;
126 private View mRightFragmentContainer
;
128 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
129 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
130 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
132 public static final int DIALOG_SHORT_WAIT
= 0;
133 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
134 private static final int DIALOG_CERT_NOT_SAVED
= 2;
136 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
138 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
139 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
140 public static final int ACTION_MOVE_FILES
= 3;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private String DIALOG_UNTRUSTED_CERT
;
153 private OCFile mWaitingToSend
;
156 protected void onCreate(Bundle savedInstanceState
) {
157 Log_OC
.d(TAG
, "onCreate() start");
158 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
160 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
162 // PIN CODE request ; best location is to decide, let's try this first
163 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
165 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
169 /// grant that FileObserverService is watching favourite files
170 if (savedInstanceState
== null
) {
171 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
172 startService(initObserversIntent
);
175 /// Load of saved instance state
176 if(savedInstanceState
!= null
) {
177 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
178 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
179 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
182 mWaitingToPreview
= null
;
183 mSyncInProgress
= false
;
184 mWaitingToSend
= null
;
189 // Inflate and set the layout view
190 setContentView(R
.layout
.files
);
191 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
192 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
193 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
194 if (savedInstanceState
== null
) {
195 createMinFragments();
199 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
200 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
201 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
205 Log_OC
.d(TAG
, "onCreate() end");
209 protected void onStart() {
211 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 protected void onDestroy() {
220 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
223 protected void onAccountSet(boolean stateWasRecovered
) {
224 super.onAccountSet(stateWasRecovered
);
225 if (getAccount() != null
) {
226 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
227 OCFile file
= getFile();
228 // get parent from path
229 String parentPath
= "";
231 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
232 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
233 // get parent from path
234 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
235 if (getStorageManager().getFileByPath(parentPath
) == null
)
236 file
= null
; // not able to know the directory where the file is uploading
238 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
242 // fall back to root folder
243 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
246 setNavigationListWithFolder(file
);
248 if (!stateWasRecovered
) {
249 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
250 initFragmentsWithFile();
251 if (file
.isFolder()) {
252 startSyncFolderOperation(file
);
256 updateFragmentsVisibility(!file
.isFolder());
257 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
263 private void setNavigationListWithFolder(OCFile file
) {
264 mDirectories
.clear();
265 OCFile fileIt
= file
;
267 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
268 if (fileIt
.isFolder()) {
269 mDirectories
.add(fileIt
.getFileName());
271 // get parent from path
272 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
273 fileIt
= getStorageManager().getFileByPath(parentPath
);
275 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
279 private void createMinFragments() {
280 OCFileListFragment listOfFiles
= new OCFileListFragment();
281 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
282 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
283 transaction
.commit();
286 private void initFragmentsWithFile() {
287 if (getAccount() != null
&& getFile() != null
) {
289 OCFileListFragment listOfFiles
= getListOfFilesFragment();
290 if (listOfFiles
!= null
) {
291 listOfFiles
.listDirectory(getCurrentDir());
293 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
297 OCFile file
= getFile();
298 Fragment secondFragment
= chooseInitialSecondFragment(file
);
299 if (secondFragment
!= null
) {
300 setSecondFragment(secondFragment
);
301 updateFragmentsVisibility(true
);
302 updateNavigationElementsInActionBar(file
);
305 cleanSecondFragment();
309 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
310 if (getAccount() == null
) {
311 Log
.wtf(TAG
, "\t account is NULL");
313 if (getFile() == null
) {
314 Log
.wtf(TAG
, "\t file is NULL");
319 private Fragment
chooseInitialSecondFragment(OCFile file
) {
320 Fragment secondFragment
= null
;
321 if (file
!= null
&& !file
.isFolder()) {
322 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
323 && file
.getLastSyncDateForProperties() > 0 // temporal fix
325 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
326 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
327 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
330 secondFragment
= new FileDetailFragment(file
, getAccount());
333 return secondFragment
;
338 * Replaces the second fragment managed by the activity with the received as
341 * Assumes never will be more than two fragments managed at the same time.
343 * @param fragment New second Fragment to set.
345 private void setSecondFragment(Fragment fragment
) {
346 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
347 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
348 transaction
.commit();
352 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
354 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
355 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
357 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
358 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
361 } else if (existsSecondFragment
) {
362 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
363 mLeftFragmentContainer
.setVisibility(View
.GONE
);
365 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
370 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
374 mRightFragmentContainer
.setVisibility(View
.GONE
);
380 private OCFileListFragment
getListOfFilesFragment() {
381 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
382 if (listOfFiles
!= null
) {
383 return (OCFileListFragment
)listOfFiles
;
385 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
389 public FileFragment
getSecondFragment() {
390 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
391 if (second
!= null
) {
392 return (FileFragment
)second
;
397 protected void cleanSecondFragment() {
398 Fragment second
= getSecondFragment();
399 if (second
!= null
) {
400 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
404 updateFragmentsVisibility(false
);
405 updateNavigationElementsInActionBar(null
);
408 protected void refreshListOfFilesFragment() {
409 OCFileListFragment fileListFragment
= getListOfFilesFragment();
410 if (fileListFragment
!= null
) {
411 fileListFragment
.listDirectory();
415 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
416 FileFragment secondFragment
= getSecondFragment();
417 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
418 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
419 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
420 OCFile fileInFragment
= detailsFragment
.getFile();
421 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
422 // the user browsed to other file ; forget the automatic preview
423 mWaitingToPreview
= null
;
425 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
426 // grant that the right panel updates the progress bar
427 detailsFragment
.listenForTransferProgress();
428 detailsFragment
.updateFileDetails(true
, false
);
430 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
431 // update the right panel
432 boolean detailsFragmentChanged
= false
;
435 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
436 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
437 startMediaPreview(mWaitingToPreview
, 0, true
);
438 detailsFragmentChanged
= true
;
440 getFileOperationsHelper().openFile(mWaitingToPreview
);
443 mWaitingToPreview
= null
;
445 if (!detailsFragmentChanged
) {
446 detailsFragment
.updateFileDetails(false
, (success
));
453 public boolean onCreateOptionsMenu(Menu menu
) {
454 MenuInflater inflater
= getSherlock().getMenuInflater();
455 inflater
.inflate(R
.menu
.main_menu
, menu
);
460 public boolean onOptionsItemSelected(MenuItem item
) {
461 boolean retval
= true
;
462 switch (item
.getItemId()) {
463 case R
.id
.action_create_dir
: {
464 CreateFolderDialogFragment dialog
=
465 CreateFolderDialogFragment
.newInstance(getCurrentDir());
466 dialog
.show(getSupportFragmentManager(), "createdirdialog");
469 case R
.id
.action_sync_account
: {
470 startSynchronization();
473 case R
.id
.action_upload
: {
474 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
477 case R
.id
.action_settings
: {
478 Intent settingsIntent
= new Intent(this, Preferences
.class);
479 startActivity(settingsIntent
);
482 case android
.R
.id
.home
: {
483 FileFragment second
= getSecondFragment();
484 OCFile currentDir
= getCurrentDir();
485 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
486 (second
!= null
&& second
.getFile() != null
)) {
493 retval
= super.onOptionsItemSelected(item
);
498 private void startSynchronization() {
499 Log_OC
.e(TAG
, "Got to start sync");
500 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
501 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
502 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
503 Bundle bundle
= new Bundle();
504 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
505 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
506 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
507 ContentResolver
.requestSync(
509 MainApp
.getAuthority(), bundle
);
511 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
512 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
513 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
514 builder
.setExpedited(true
);
515 builder
.setManual(true
);
517 SyncRequest request
= builder
.build();
518 ContentResolver
.requestSync(request
);
524 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
525 if (itemPosition
!= 0) {
526 String targetPath
= "";
527 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
528 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
530 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
531 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
532 if (targetFolder
!= null
) {
533 browseTo(targetFolder
);
536 // the next operation triggers a new call to this method, but it's necessary to
537 // ensure that the name exposed in the action bar is the current directory when the
538 // user selected it in the navigation list
539 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
540 getSupportActionBar().setSelectedNavigationItem(0);
546 * Called, when the user selected something for uploading
548 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
549 super.onActivityResult(requestCode
, resultCode
, data
);
551 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
552 requestSimpleUpload(data
, resultCode
);
554 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
555 requestMultipleUpload(data
, resultCode
);
557 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
558 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
559 requestMoveOperation(data
, resultCode
);
563 private void requestMultipleUpload(Intent data
, int resultCode
) {
564 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
565 if (filePaths
!= null
) {
566 String
[] remotePaths
= new String
[filePaths
.length
];
567 String remotePathBase
= "";
568 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
569 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
571 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
572 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
573 for (int j
= 0; j
< remotePaths
.length
; j
++) {
574 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
577 Intent i
= new Intent(this, FileUploader
.class);
578 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
579 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
580 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
581 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
582 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
583 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
587 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
588 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
595 private void requestSimpleUpload(Intent data
, int resultCode
) {
596 String filepath
= null
;
598 Uri selectedImageUri
= data
.getData();
600 String filemanagerstring
= selectedImageUri
.getPath();
601 String selectedImagePath
= getPath(selectedImageUri
);
603 if (selectedImagePath
!= null
)
604 filepath
= selectedImagePath
;
606 filepath
= filemanagerstring
;
608 } catch (Exception e
) {
609 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
613 if (filepath
== null
) {
614 Log_OC
.e(TAG
, "Couldnt resolve path to file");
615 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
621 Intent i
= new Intent(this, FileUploader
.class);
622 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
624 String remotepath
= new String();
625 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
626 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
628 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
629 remotepath
+= OCFile
.PATH_SEPARATOR
;
630 remotepath
+= new File(filepath
).getName();
632 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
633 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
634 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
635 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
636 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
641 * Request the operation for moving the file/folder from one path to another
643 * @param data Intent received
644 * @param resultCode Result code received
646 private void requestMoveOperation(Intent data
, int resultCode
) {
647 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
648 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
649 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
653 public void onBackPressed() {
654 OCFileListFragment listOfFiles
= getListOfFilesFragment();
655 if (mDualPane
|| getSecondFragment() == null
) {
656 if (listOfFiles
!= null
) { // should never be null, indeed
657 if (mDirectories
.getCount() <= 1) {
661 int levelsUp
= listOfFiles
.onBrowseUp();
662 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
667 if (listOfFiles
!= null
) { // should never be null, indeed
668 setFile(listOfFiles
.getCurrentFile());
670 cleanSecondFragment();
675 protected void onSaveInstanceState(Bundle outState
) {
676 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
677 Log_OC
.e(TAG
, "onSaveInstanceState() start");
678 super.onSaveInstanceState(outState
);
679 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
680 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
681 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
682 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
684 Log_OC
.d(TAG
, "onSaveInstanceState() end");
690 protected void onResume() {
692 Log_OC
.e(TAG
, "onResume() start");
694 // refresh list of files
695 refreshListOfFilesFragment();
697 // Listen for sync messages
698 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
699 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
700 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
701 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
702 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
703 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
704 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
705 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
707 // Listen for upload messages
708 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
709 mUploadFinishReceiver
= new UploadFinishReceiver();
710 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
712 // Listen for download messages
713 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
714 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
715 mDownloadFinishReceiver
= new DownloadFinishReceiver();
716 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
718 Log_OC
.d(TAG
, "onResume() end");
723 protected void onPause() {
724 Log_OC
.e(TAG
, "onPause() start");
725 if (mSyncBroadcastReceiver
!= null
) {
726 unregisterReceiver(mSyncBroadcastReceiver
);
727 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
728 mSyncBroadcastReceiver
= null
;
730 if (mUploadFinishReceiver
!= null
) {
731 unregisterReceiver(mUploadFinishReceiver
);
732 mUploadFinishReceiver
= null
;
734 if (mDownloadFinishReceiver
!= null
) {
735 unregisterReceiver(mDownloadFinishReceiver
);
736 mDownloadFinishReceiver
= null
;
740 Log_OC
.d(TAG
, "onPause() end");
746 protected Dialog
onCreateDialog(int id
) {
747 Dialog dialog
= null
;
748 AlertDialog
.Builder builder
;
750 case DIALOG_SHORT_WAIT
: {
751 ProgressDialog working_dialog
= new ProgressDialog(this);
752 working_dialog
.setMessage(getResources().getString(
753 R
.string
.wait_a_moment
));
754 working_dialog
.setIndeterminate(true
);
755 working_dialog
.setCancelable(false
);
756 dialog
= working_dialog
;
759 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
762 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
763 getString(R
.string
.actionbar_upload_from_apps
) };
765 builder
= new AlertDialog
.Builder(this);
766 builder
.setTitle(R
.string
.actionbar_upload
);
767 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
768 public void onClick(DialogInterface dialog
, int item
) {
771 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
772 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
773 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
775 // TODO create and handle new fragment
776 // LocalFileListFragment
778 } else if (item
== 1) {
779 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
780 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
781 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
782 ACTION_SELECT_CONTENT_FROM_APPS
);
786 dialog
= builder
.create();
789 case DIALOG_CERT_NOT_SAVED
: {
790 builder
= new AlertDialog
.Builder(this);
791 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
792 builder
.setCancelable(false
);
793 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
795 public void onClick(DialogInterface dialog
, int which
) {
799 dialog
= builder
.create();
811 * Translates a content URI of an image to a physical path
813 * @param uri The URI to resolve
814 * @return The path to the image or null if it could not be found
816 public String
getPath(Uri uri
) {
817 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
818 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
819 if (cursor
!= null
) {
820 int column_index
= cursor
821 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
822 cursor
.moveToFirst();
823 return cursor
.getString(column_index
);
829 * Pushes a directory to the drop down list
830 * @param directory to push
831 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
833 public void pushDirname(OCFile directory
) {
834 if(!directory
.isFolder()){
835 throw new IllegalArgumentException("Only directories may be pushed!");
837 mDirectories
.insert(directory
.getFileName(), 0);
842 * Pops a directory name from the drop down list
843 * @return True, unless the stack is empty
845 public boolean popDirname() {
846 mDirectories
.remove(mDirectories
.getItem(0));
847 return !mDirectories
.isEmpty();
850 // Custom array adapter to override text colors
851 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
853 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
857 public View
getView(int position
, View convertView
, ViewGroup parent
) {
858 View v
= super.getView(position
, convertView
, parent
);
860 ((TextView
) v
).setTextColor(getResources().getColorStateList(
861 android
.R
.color
.white
));
863 fixRoot((TextView
) v
);
867 public View
getDropDownView(int position
, View convertView
,
869 View v
= super.getDropDownView(position
, convertView
, parent
);
871 ((TextView
) v
).setTextColor(getResources().getColorStateList(
872 android
.R
.color
.white
));
874 fixRoot((TextView
) v
);
878 private void fixRoot(TextView v
) {
879 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
880 v
.setText(R
.string
.default_display_name_for_root_folder
);
886 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
889 * {@link BroadcastReceiver} to enable syncing feedback in UI
892 public void onReceive(Context context
, Intent intent
) {
894 String event
= intent
.getAction();
895 Log_OC
.d(TAG
, "Received broadcast " + event
);
896 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
897 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
898 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
899 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
903 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
904 mSyncInProgress
= true
;
907 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
908 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
910 if (currentDir
== null
) {
911 // current folder was removed from the server
912 Toast
.makeText( FileDisplayActivity
.this,
913 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
919 if (currentFile
== null
&& !getFile().isFolder()) {
920 // currently selected file was removed in the server, and now we know it
921 cleanSecondFragment();
922 currentFile
= currentDir
;
925 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
926 OCFileListFragment fileListFragment
= getListOfFilesFragment();
927 if (fileListFragment
!= null
) {
928 fileListFragment
.listDirectory(currentDir
);
931 setFile(currentFile
);
934 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
936 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
938 /// TODO refactor and make common
939 synchResult
!= null
&& !synchResult
.isSuccess() &&
940 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
941 synchResult
.isIdPRedirection() ||
942 (synchResult
.isException() && synchResult
.getException()
943 instanceof AuthenticatorException
))) {
945 OwnCloudClient client
= null
;
947 OwnCloudAccount ocAccount
=
948 new OwnCloudAccount(getAccount(), context
);
949 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
950 removeClientFor(ocAccount
));
951 // TODO get rid of these exceptions
952 } catch (AccountNotFoundException e
) {
954 } catch (AuthenticatorException e
) {
956 } catch (OperationCanceledException e
) {
958 } catch (IOException e
) {
962 if (client
!= null
) {
963 OwnCloudCredentials cred
= client
.getCredentials();
965 AccountManager am
= AccountManager
.get(context
);
966 if (cred
.authTokenExpires()) {
967 am
.invalidateAuthToken(
972 am
.clearPassword(getAccount());
977 requestCredentialsUpdate();
981 removeStickyBroadcast(intent
);
982 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
983 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
989 if (synchResult
!= null
) {
990 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
991 mLastSslUntrustedServerResult
= synchResult
;
994 } catch (RuntimeException e
) {
995 // avoid app crashes after changing the serial id of RemoteOperationResult
996 // in owncloud library with broadcast notifications pending to process
997 removeStickyBroadcast(intent
);
1003 * Show a text message on screen view for notifying user if content is
1004 * loading or folder is empty
1006 private void setBackgroundText() {
1007 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1008 if (ocFileListFragment
!= null
) {
1009 int message
= R
.string
.file_list_loading
;
1010 if (!mSyncInProgress
) {
1011 // In case file list is empty
1012 message
= R
.string
.file_list_empty
;
1014 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1016 Log
.e(TAG
, "OCFileListFragment is null");
1021 * Once the file upload has finished -> update view
1023 private class UploadFinishReceiver
extends BroadcastReceiver
{
1025 * Once the file upload has finished -> update view
1026 * @author David A. Velasco
1027 * {@link BroadcastReceiver} to enable upload feedback in UI
1030 public void onReceive(Context context
, Intent intent
) {
1032 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1033 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1034 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1035 OCFile currentDir
= getCurrentDir();
1036 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1037 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1039 if (sameAccount
&& isDescendant
) {
1040 refreshListOfFilesFragment();
1043 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1044 boolean renamedInUpload
= getFile().getRemotePath().
1045 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1046 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1048 FileFragment details
= getSecondFragment();
1049 boolean detailFragmentIsShown
= (details
!= null
&&
1050 details
instanceof FileDetailFragment
);
1052 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1053 if (uploadWasFine
) {
1054 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1056 if (renamedInUpload
) {
1057 String newName
= (new File(uploadedRemotePath
)).getName();
1058 Toast msg
= Toast
.makeText(
1061 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1066 if (uploadWasFine
|| getFile().fileExists()) {
1067 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1069 cleanSecondFragment();
1072 // Force the preview if the file is an image
1073 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1074 startImagePreview(getFile());
1075 } // TODO what about other kind of previews?
1079 if (intent
!= null
) {
1080 removeStickyBroadcast(intent
);
1090 * Class waiting for broadcast events from the {@link FielDownloader} service.
1092 * Updates the UI when a download is started or finished, provided that it is relevant for the
1095 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1097 public void onReceive(Context context
, Intent intent
) {
1099 boolean sameAccount
= isSameAccount(context
, intent
);
1100 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1101 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1103 if (sameAccount
&& isDescendant
) {
1104 refreshListOfFilesFragment();
1105 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1108 if (mWaitingToSend
!= null
) {
1109 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1110 if (mWaitingToSend
.isDown()) {
1111 sendDownloadedFile();
1116 if (intent
!= null
) {
1117 removeStickyBroadcast(intent
);
1122 private boolean isDescendant(String downloadedRemotePath
) {
1123 OCFile currentDir
= getCurrentDir();
1124 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1127 private boolean isSameAccount(Context context
, Intent intent
) {
1128 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1129 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1134 public void browseToRoot() {
1135 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1136 if (listOfFiles
!= null
) { // should never be null, indeed
1137 while (mDirectories
.getCount() > 1) {
1140 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1141 listOfFiles
.listDirectory(root
);
1142 setFile(listOfFiles
.getCurrentFile());
1143 startSyncFolderOperation(root
);
1145 cleanSecondFragment();
1149 public void browseTo(OCFile folder
) {
1150 if (folder
== null
|| !folder
.isFolder()) {
1151 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1153 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1154 if (listOfFiles
!= null
) {
1155 setNavigationListWithFolder(folder
);
1156 listOfFiles
.listDirectory(folder
);
1157 setFile(listOfFiles
.getCurrentFile());
1158 startSyncFolderOperation(folder
);
1160 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1162 cleanSecondFragment();
1169 * Updates action bar and second fragment, if in dual pane mode.
1172 public void onBrowsedDownTo(OCFile directory
) {
1173 pushDirname(directory
);
1174 cleanSecondFragment();
1177 startSyncFolderOperation(directory
);
1182 * Shows the information of the {@link OCFile} received as a
1183 * parameter in the second fragment.
1185 * @param file {@link OCFile} whose details will be shown
1188 public void showDetails(OCFile file
) {
1189 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1190 setSecondFragment(detailFragment
);
1191 updateFragmentsVisibility(true
);
1192 updateNavigationElementsInActionBar(file
);
1200 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1201 ActionBar actionBar
= getSupportActionBar();
1202 if (chosenFile
== null
|| mDualPane
) {
1203 // only list of files - set for browsing through folders
1204 OCFile currentDir
= getCurrentDir();
1205 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1206 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1207 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1209 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1211 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1212 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1215 actionBar
.setDisplayHomeAsUpEnabled(true
);
1216 actionBar
.setDisplayShowTitleEnabled(true
);
1217 actionBar
.setTitle(chosenFile
.getFileName());
1218 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1224 protected ServiceConnection
newTransferenceServiceConnection() {
1225 return new ListServiceConnection();
1228 /** Defines callbacks for service binding, passed to bindService() */
1229 private class ListServiceConnection
implements ServiceConnection
{
1232 public void onServiceConnected(ComponentName component
, IBinder service
) {
1233 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1234 Log_OC
.d(TAG
, "Download service connected");
1235 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1236 if (mWaitingToPreview
!= null
)
1237 if (getStorageManager() != null
) {
1238 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1239 if (!mWaitingToPreview
.isDown()) {
1240 requestForDownload();
1244 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1245 Log_OC
.d(TAG
, "Upload service connected");
1246 mUploaderBinder
= (FileUploaderBinder
) service
;
1250 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1251 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1252 if (listOfFiles
!= null
) {
1253 listOfFiles
.listDirectory();
1255 FileFragment secondFragment
= getSecondFragment();
1256 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1257 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1258 detailFragment
.listenForTransferProgress();
1259 detailFragment
.updateFileDetails(false
, false
);
1264 public void onServiceDisconnected(ComponentName component
) {
1265 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1266 Log_OC
.d(TAG
, "Download service disconnected");
1267 mDownloaderBinder
= null
;
1268 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1269 Log_OC
.d(TAG
, "Upload service disconnected");
1270 mUploaderBinder
= null
;
1278 * Launch an intent to request the PIN code to the user before letting him use the app
1280 private void requestPinCode() {
1281 boolean pinStart
= false
;
1282 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1283 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1285 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1286 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1293 public void onSavedCertificate() {
1294 startSyncFolderOperation(getCurrentDir());
1299 public void onFailedSavingCertificate() {
1300 showDialog(DIALOG_CERT_NOT_SAVED
);
1304 public void onCancelCertificate() {
1309 * Updates the view associated to the activity after the finish of some operation over files
1310 * in the current account.
1312 * @param operation Removal operation performed.
1313 * @param result Result of the removal.
1316 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1317 super.onRemoteOperationFinish(operation
, result
);
1319 if (operation
instanceof RemoveFileOperation
) {
1320 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1322 } else if (operation
instanceof RenameFileOperation
) {
1323 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1325 } else if (operation
instanceof SynchronizeFileOperation
) {
1326 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1328 } else if (operation
instanceof CreateFolderOperation
) {
1329 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1331 } else if (operation
instanceof CreateShareOperation
) {
1332 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1334 } else if (operation
instanceof UnshareLinkOperation
) {
1335 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1337 } else if (operation
instanceof MoveFileOperation
) {
1338 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1344 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1345 if (result
.isSuccess()) {
1346 refreshShowDetails();
1347 refreshListOfFilesFragment();
1352 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1353 if (result
.isSuccess()) {
1354 refreshShowDetails();
1355 refreshListOfFilesFragment();
1357 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1358 cleanSecondFragment();
1359 refreshListOfFilesFragment();
1363 private void refreshShowDetails() {
1364 FileFragment details
= getSecondFragment();
1365 if (details
!= null
) {
1366 OCFile file
= details
.getFile();
1368 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1369 if (details
instanceof PreviewMediaFragment
) {
1370 // Refresh OCFile of the fragment
1371 ((PreviewMediaFragment
) details
).updateFile(file
);
1376 invalidateOptionsMenu();
1381 * Updates the view associated to the activity after the finish of an operation trying to remove a
1384 * @param operation Removal operation performed.
1385 * @param result Result of the removal.
1387 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1388 dismissLoadingDialog();
1390 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1394 if (result
.isSuccess()) {
1395 OCFile removedFile
= operation
.getFile();
1396 FileFragment second
= getSecondFragment();
1397 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1398 if (second
instanceof PreviewMediaFragment
) {
1399 ((PreviewMediaFragment
)second
).stopPreview(true
);
1401 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1402 cleanSecondFragment();
1404 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1405 refreshListOfFilesFragment();
1407 invalidateOptionsMenu();
1409 if (result
.isSslRecoverableException()) {
1410 mLastSslUntrustedServerResult
= result
;
1411 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1418 * Updates the view associated to the activity after the finish of an operation trying to move a
1421 * @param operation Move operation performed.
1422 * @param result Result of the move operation.
1424 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1425 if (result
.isSuccess()) {
1426 dismissLoadingDialog();
1427 refreshListOfFilesFragment();
1429 dismissLoadingDialog();
1431 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1432 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1436 } catch (NotFoundException e
) {
1437 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1444 * Updates the view associated to the activity after the finish of an operation trying to rename a
1447 * @param operation Renaming operation performed.
1448 * @param result Result of the renaming.
1450 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1451 dismissLoadingDialog();
1452 OCFile renamedFile
= operation
.getFile();
1453 if (result
.isSuccess()) {
1454 FileFragment details
= getSecondFragment();
1455 if (details
!= null
) {
1456 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1457 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1458 showDetails(renamedFile
);
1460 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1461 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1462 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1463 int position
= ((PreviewMediaFragment
)details
).getPosition();
1464 startMediaPreview(renamedFile
, position
, true
);
1466 getFileOperationsHelper().openFile(renamedFile
);
1471 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1472 refreshListOfFilesFragment();
1476 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1480 if (result
.isSslRecoverableException()) {
1481 mLastSslUntrustedServerResult
= result
;
1482 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1487 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1488 dismissLoadingDialog();
1489 OCFile syncedFile
= operation
.getLocalFile();
1490 if (!result
.isSuccess()) {
1491 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1492 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1493 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1494 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1500 if (operation
.transferWasRequested()) {
1501 onTransferStateChanged(syncedFile
, true
, true
);
1504 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1512 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1514 * @param operation Creation operation performed.
1515 * @param result Result of the creation.
1517 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1518 if (result
.isSuccess()) {
1519 dismissLoadingDialog();
1520 refreshListOfFilesFragment();
1522 dismissLoadingDialog();
1524 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1525 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1529 } catch (NotFoundException e
) {
1530 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1540 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1541 refreshListOfFilesFragment();
1542 FileFragment details
= getSecondFragment();
1543 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1544 if (downloading
|| uploading
) {
1545 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1547 if (!file
.fileExists()) {
1548 cleanSecondFragment();
1550 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1558 private void requestForDownload() {
1559 Account account
= getAccount();
1560 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1561 Intent i
= new Intent(this, FileDownloader
.class);
1562 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1563 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1569 private OCFile
getCurrentDir() {
1570 OCFile file
= getFile();
1572 if (file
.isFolder()) {
1574 } else if (getStorageManager() != null
) {
1575 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1576 return getStorageManager().getFileByPath(parentPath
);
1582 public void startSyncFolderOperation(OCFile folder
) {
1583 long currentSyncTime
= System
.currentTimeMillis();
1585 mSyncInProgress
= true
;
1587 // perform folder synchronization
1588 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1591 getFileOperationsHelper().isSharedSupported(),
1592 getStorageManager(),
1594 getApplicationContext()
1596 synchFolderOp
.execute(getAccount(), this, null
, null
);
1598 setSupportProgressBarIndeterminateVisibility(true
);
1600 setBackgroundText();
1604 * Show untrusted cert dialog
1606 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1607 // Show a dialog with the certificate info
1608 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1609 FragmentManager fm
= getSupportFragmentManager();
1610 FragmentTransaction ft
= fm
.beginTransaction();
1611 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1614 private void requestForDownload(OCFile file
) {
1615 Account account
= getAccount();
1616 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1617 Intent i
= new Intent(this, FileDownloader
.class);
1618 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1619 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1624 private void sendDownloadedFile(){
1625 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1626 mWaitingToSend
= null
;
1631 * Requests the download of the received {@link OCFile} , updates the UI
1632 * to monitor the download progress and prepares the activity to send the file
1633 * when the download finishes.
1635 * @param file {@link OCFile} to download and preview.
1637 public void startDownloadForSending(OCFile file
) {
1638 mWaitingToSend
= file
;
1639 requestForDownload(mWaitingToSend
);
1640 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1641 updateFragmentsVisibility(hasSecondFragment
);
1645 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1647 * @param file Image {@link OCFile} to show.
1649 public void startImagePreview(OCFile file
) {
1650 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1651 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1652 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1653 startActivity(showDetailsIntent
);
1658 * Stars the preview of an already down media {@link OCFile}.
1660 * @param file Media {@link OCFile} to preview.
1661 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1662 * @param autoplay When 'true', the playback will start without user interactions.
1664 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1665 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1666 setSecondFragment(mediaFragment
);
1667 updateFragmentsVisibility(true
);
1668 updateNavigationElementsInActionBar(file
);
1673 * Requests the download of the received {@link OCFile} , updates the UI
1674 * to monitor the download progress and prepares the activity to preview
1675 * or open the file when the download finishes.
1677 * @param file {@link OCFile} to download and preview.
1679 public void startDownloadForPreview(OCFile file
) {
1680 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1681 setSecondFragment(detailFragment
);
1682 mWaitingToPreview
= file
;
1683 requestForDownload();
1684 updateFragmentsVisibility(true
);
1685 updateNavigationElementsInActionBar(file
);
1690 public void cancelTransference(OCFile file
) {
1691 getFileOperationsHelper().cancelTransference(file
);
1692 if (mWaitingToPreview
!= null
&&
1693 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1694 mWaitingToPreview
= null
;
1696 if (mWaitingToSend
!= null
&&
1697 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1698 mWaitingToSend
= null
;
1700 onTransferStateChanged(file
, false
, false
);
1704 public void onRefresh() {
1705 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1706 if (listOfFiles
!= null
) {
1707 OCFile folder
= listOfFiles
.getCurrentFile();
1708 if (folder
!= null
) {
1709 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1710 listDirectory(mFile);*/
1711 startSyncFolderOperation(folder
);