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 getFileOperationsHelper().moveFile(folderToMoveAt
, getCurrentDir());
652 public void onBackPressed() {
653 OCFileListFragment listOfFiles
= getListOfFilesFragment();
654 if (mDualPane
|| getSecondFragment() == null
) {
655 if (listOfFiles
!= null
) { // should never be null, indeed
656 if (mDirectories
.getCount() <= 1) {
660 int levelsUp
= listOfFiles
.onBrowseUp();
661 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
666 if (listOfFiles
!= null
) { // should never be null, indeed
667 setFile(listOfFiles
.getCurrentFile());
669 cleanSecondFragment();
674 protected void onSaveInstanceState(Bundle outState
) {
675 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
676 Log_OC
.e(TAG
, "onSaveInstanceState() start");
677 super.onSaveInstanceState(outState
);
678 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
679 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
680 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
681 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
683 Log_OC
.d(TAG
, "onSaveInstanceState() end");
689 protected void onResume() {
691 Log_OC
.e(TAG
, "onResume() start");
693 // refresh list of files
694 refreshListOfFilesFragment();
696 // Listen for sync messages
697 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
698 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
699 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
700 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
701 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
702 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
703 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
704 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
706 // Listen for upload messages
707 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
708 mUploadFinishReceiver
= new UploadFinishReceiver();
709 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
711 // Listen for download messages
712 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
713 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
714 mDownloadFinishReceiver
= new DownloadFinishReceiver();
715 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
717 Log_OC
.d(TAG
, "onResume() end");
722 protected void onPause() {
723 Log_OC
.e(TAG
, "onPause() start");
724 if (mSyncBroadcastReceiver
!= null
) {
725 unregisterReceiver(mSyncBroadcastReceiver
);
726 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
727 mSyncBroadcastReceiver
= null
;
729 if (mUploadFinishReceiver
!= null
) {
730 unregisterReceiver(mUploadFinishReceiver
);
731 mUploadFinishReceiver
= null
;
733 if (mDownloadFinishReceiver
!= null
) {
734 unregisterReceiver(mDownloadFinishReceiver
);
735 mDownloadFinishReceiver
= null
;
739 Log_OC
.d(TAG
, "onPause() end");
745 protected Dialog
onCreateDialog(int id
) {
746 Dialog dialog
= null
;
747 AlertDialog
.Builder builder
;
749 case DIALOG_SHORT_WAIT
: {
750 ProgressDialog working_dialog
= new ProgressDialog(this);
751 working_dialog
.setMessage(getResources().getString(
752 R
.string
.wait_a_moment
));
753 working_dialog
.setIndeterminate(true
);
754 working_dialog
.setCancelable(false
);
755 dialog
= working_dialog
;
758 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
761 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
762 getString(R
.string
.actionbar_upload_from_apps
) };
764 builder
= new AlertDialog
.Builder(this);
765 builder
.setTitle(R
.string
.actionbar_upload
);
766 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
767 public void onClick(DialogInterface dialog
, int item
) {
770 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
771 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
772 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
774 // TODO create and handle new fragment
775 // LocalFileListFragment
777 } else if (item
== 1) {
778 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
779 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
780 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
781 ACTION_SELECT_CONTENT_FROM_APPS
);
785 dialog
= builder
.create();
788 case DIALOG_CERT_NOT_SAVED
: {
789 builder
= new AlertDialog
.Builder(this);
790 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
791 builder
.setCancelable(false
);
792 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
794 public void onClick(DialogInterface dialog
, int which
) {
798 dialog
= builder
.create();
810 * Translates a content URI of an image to a physical path
812 * @param uri The URI to resolve
813 * @return The path to the image or null if it could not be found
815 public String
getPath(Uri uri
) {
816 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
817 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
818 if (cursor
!= null
) {
819 int column_index
= cursor
820 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
821 cursor
.moveToFirst();
822 return cursor
.getString(column_index
);
828 * Pushes a directory to the drop down list
829 * @param directory to push
830 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
832 public void pushDirname(OCFile directory
) {
833 if(!directory
.isFolder()){
834 throw new IllegalArgumentException("Only directories may be pushed!");
836 mDirectories
.insert(directory
.getFileName(), 0);
841 * Pops a directory name from the drop down list
842 * @return True, unless the stack is empty
844 public boolean popDirname() {
845 mDirectories
.remove(mDirectories
.getItem(0));
846 return !mDirectories
.isEmpty();
849 // Custom array adapter to override text colors
850 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
852 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
856 public View
getView(int position
, View convertView
, ViewGroup parent
) {
857 View v
= super.getView(position
, convertView
, parent
);
859 ((TextView
) v
).setTextColor(getResources().getColorStateList(
860 android
.R
.color
.white
));
862 fixRoot((TextView
) v
);
866 public View
getDropDownView(int position
, View convertView
,
868 View v
= super.getDropDownView(position
, convertView
, parent
);
870 ((TextView
) v
).setTextColor(getResources().getColorStateList(
871 android
.R
.color
.white
));
873 fixRoot((TextView
) v
);
877 private void fixRoot(TextView v
) {
878 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
879 v
.setText(R
.string
.default_display_name_for_root_folder
);
885 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
888 * {@link BroadcastReceiver} to enable syncing feedback in UI
891 public void onReceive(Context context
, Intent intent
) {
893 String event
= intent
.getAction();
894 Log_OC
.d(TAG
, "Received broadcast " + event
);
895 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
896 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
897 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
898 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
902 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
903 mSyncInProgress
= true
;
906 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
907 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
909 if (currentDir
== null
) {
910 // current folder was removed from the server
911 Toast
.makeText( FileDisplayActivity
.this,
912 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
918 if (currentFile
== null
&& !getFile().isFolder()) {
919 // currently selected file was removed in the server, and now we know it
920 cleanSecondFragment();
921 currentFile
= currentDir
;
924 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
925 OCFileListFragment fileListFragment
= getListOfFilesFragment();
926 if (fileListFragment
!= null
) {
927 fileListFragment
.listDirectory(currentDir
);
930 setFile(currentFile
);
933 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
935 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
937 /// TODO refactor and make common
938 synchResult
!= null
&& !synchResult
.isSuccess() &&
939 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
940 synchResult
.isIdPRedirection() ||
941 (synchResult
.isException() && synchResult
.getException()
942 instanceof AuthenticatorException
))) {
944 OwnCloudClient client
= null
;
946 OwnCloudAccount ocAccount
=
947 new OwnCloudAccount(getAccount(), context
);
948 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
949 removeClientFor(ocAccount
));
950 // TODO get rid of these exceptions
951 } catch (AccountNotFoundException e
) {
953 } catch (AuthenticatorException e
) {
955 } catch (OperationCanceledException e
) {
957 } catch (IOException e
) {
961 if (client
!= null
) {
962 OwnCloudCredentials cred
= client
.getCredentials();
964 AccountManager am
= AccountManager
.get(context
);
965 if (cred
.authTokenExpires()) {
966 am
.invalidateAuthToken(
971 am
.clearPassword(getAccount());
976 requestCredentialsUpdate();
980 removeStickyBroadcast(intent
);
981 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
982 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
988 if (synchResult
!= null
) {
989 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
990 mLastSslUntrustedServerResult
= synchResult
;
993 } catch (RuntimeException e
) {
994 // avoid app crashes after changing the serial id of RemoteOperationResult
995 // in owncloud library with broadcast notifications pending to process
996 removeStickyBroadcast(intent
);
1002 * Show a text message on screen view for notifying user if content is
1003 * loading or folder is empty
1005 private void setBackgroundText() {
1006 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1007 if (ocFileListFragment
!= null
) {
1008 int message
= R
.string
.file_list_loading
;
1009 if (!mSyncInProgress
) {
1010 // In case file list is empty
1011 message
= R
.string
.file_list_empty
;
1013 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1015 Log
.e(TAG
, "OCFileListFragment is null");
1020 * Once the file upload has finished -> update view
1022 private class UploadFinishReceiver
extends BroadcastReceiver
{
1024 * Once the file upload has finished -> update view
1025 * @author David A. Velasco
1026 * {@link BroadcastReceiver} to enable upload feedback in UI
1029 public void onReceive(Context context
, Intent intent
) {
1031 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1032 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1033 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1034 OCFile currentDir
= getCurrentDir();
1035 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1036 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1038 if (sameAccount
&& isDescendant
) {
1039 refreshListOfFilesFragment();
1042 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1043 boolean renamedInUpload
= getFile().getRemotePath().
1044 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1045 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1047 FileFragment details
= getSecondFragment();
1048 boolean detailFragmentIsShown
= (details
!= null
&&
1049 details
instanceof FileDetailFragment
);
1051 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1052 if (uploadWasFine
) {
1053 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1055 if (renamedInUpload
) {
1056 String newName
= (new File(uploadedRemotePath
)).getName();
1057 Toast msg
= Toast
.makeText(
1060 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1065 if (uploadWasFine
|| getFile().fileExists()) {
1066 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1068 cleanSecondFragment();
1071 // Force the preview if the file is an image
1072 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1073 startImagePreview(getFile());
1074 } // TODO what about other kind of previews?
1078 if (intent
!= null
) {
1079 removeStickyBroadcast(intent
);
1089 * Class waiting for broadcast events from the {@link FielDownloader} service.
1091 * Updates the UI when a download is started or finished, provided that it is relevant for the
1094 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1096 public void onReceive(Context context
, Intent intent
) {
1098 boolean sameAccount
= isSameAccount(context
, intent
);
1099 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1100 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1102 if (sameAccount
&& isDescendant
) {
1103 refreshListOfFilesFragment();
1104 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1107 if (mWaitingToSend
!= null
) {
1108 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1109 if (mWaitingToSend
.isDown()) {
1110 sendDownloadedFile();
1115 if (intent
!= null
) {
1116 removeStickyBroadcast(intent
);
1121 private boolean isDescendant(String downloadedRemotePath
) {
1122 OCFile currentDir
= getCurrentDir();
1123 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1126 private boolean isSameAccount(Context context
, Intent intent
) {
1127 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1128 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1133 public void browseToRoot() {
1134 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1135 if (listOfFiles
!= null
) { // should never be null, indeed
1136 while (mDirectories
.getCount() > 1) {
1139 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1140 listOfFiles
.listDirectory(root
);
1141 setFile(listOfFiles
.getCurrentFile());
1142 startSyncFolderOperation(root
);
1144 cleanSecondFragment();
1148 public void browseTo(OCFile folder
) {
1149 if (folder
== null
|| !folder
.isFolder()) {
1150 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1152 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1153 if (listOfFiles
!= null
) {
1154 setNavigationListWithFolder(folder
);
1155 listOfFiles
.listDirectory(folder
);
1156 setFile(listOfFiles
.getCurrentFile());
1157 startSyncFolderOperation(folder
);
1159 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1161 cleanSecondFragment();
1168 * Updates action bar and second fragment, if in dual pane mode.
1171 public void onBrowsedDownTo(OCFile directory
) {
1172 pushDirname(directory
);
1173 cleanSecondFragment();
1176 startSyncFolderOperation(directory
);
1181 * Shows the information of the {@link OCFile} received as a
1182 * parameter in the second fragment.
1184 * @param file {@link OCFile} whose details will be shown
1187 public void showDetails(OCFile file
) {
1188 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1189 setSecondFragment(detailFragment
);
1190 updateFragmentsVisibility(true
);
1191 updateNavigationElementsInActionBar(file
);
1199 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1200 ActionBar actionBar
= getSupportActionBar();
1201 if (chosenFile
== null
|| mDualPane
) {
1202 // only list of files - set for browsing through folders
1203 OCFile currentDir
= getCurrentDir();
1204 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1205 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1206 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1208 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1210 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1211 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1214 actionBar
.setDisplayHomeAsUpEnabled(true
);
1215 actionBar
.setDisplayShowTitleEnabled(true
);
1216 actionBar
.setTitle(chosenFile
.getFileName());
1217 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1223 protected ServiceConnection
newTransferenceServiceConnection() {
1224 return new ListServiceConnection();
1227 /** Defines callbacks for service binding, passed to bindService() */
1228 private class ListServiceConnection
implements ServiceConnection
{
1231 public void onServiceConnected(ComponentName component
, IBinder service
) {
1232 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1233 Log_OC
.d(TAG
, "Download service connected");
1234 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1235 if (mWaitingToPreview
!= null
)
1236 if (getStorageManager() != null
) {
1237 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1238 if (!mWaitingToPreview
.isDown()) {
1239 requestForDownload();
1243 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1244 Log_OC
.d(TAG
, "Upload service connected");
1245 mUploaderBinder
= (FileUploaderBinder
) service
;
1249 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1250 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1251 if (listOfFiles
!= null
) {
1252 listOfFiles
.listDirectory();
1254 FileFragment secondFragment
= getSecondFragment();
1255 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1256 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1257 detailFragment
.listenForTransferProgress();
1258 detailFragment
.updateFileDetails(false
, false
);
1263 public void onServiceDisconnected(ComponentName component
) {
1264 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1265 Log_OC
.d(TAG
, "Download service disconnected");
1266 mDownloaderBinder
= null
;
1267 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1268 Log_OC
.d(TAG
, "Upload service disconnected");
1269 mUploaderBinder
= null
;
1277 * Launch an intent to request the PIN code to the user before letting him use the app
1279 private void requestPinCode() {
1280 boolean pinStart
= false
;
1281 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1282 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1284 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1285 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1292 public void onSavedCertificate() {
1293 startSyncFolderOperation(getCurrentDir());
1298 public void onFailedSavingCertificate() {
1299 showDialog(DIALOG_CERT_NOT_SAVED
);
1303 public void onCancelCertificate() {
1308 * Updates the view associated to the activity after the finish of some operation over files
1309 * in the current account.
1311 * @param operation Removal operation performed.
1312 * @param result Result of the removal.
1315 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1316 super.onRemoteOperationFinish(operation
, result
);
1318 if (operation
instanceof RemoveFileOperation
) {
1319 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1321 } else if (operation
instanceof RenameFileOperation
) {
1322 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1324 } else if (operation
instanceof SynchronizeFileOperation
) {
1325 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1327 } else if (operation
instanceof CreateFolderOperation
) {
1328 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1330 } else if (operation
instanceof CreateShareOperation
) {
1331 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1333 } else if (operation
instanceof UnshareLinkOperation
) {
1334 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1336 } else if (operation
instanceof MoveFileOperation
) {
1337 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1343 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1344 if (result
.isSuccess()) {
1345 refreshShowDetails();
1346 refreshListOfFilesFragment();
1351 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1352 if (result
.isSuccess()) {
1353 refreshShowDetails();
1354 refreshListOfFilesFragment();
1356 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1357 cleanSecondFragment();
1358 refreshListOfFilesFragment();
1362 private void refreshShowDetails() {
1363 FileFragment details
= getSecondFragment();
1364 if (details
!= null
) {
1365 OCFile file
= details
.getFile();
1367 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1368 if (details
instanceof PreviewMediaFragment
) {
1369 // Refresh OCFile of the fragment
1370 ((PreviewMediaFragment
) details
).updateFile(file
);
1375 invalidateOptionsMenu();
1380 * Updates the view associated to the activity after the finish of an operation trying to remove a
1383 * @param operation Removal operation performed.
1384 * @param result Result of the removal.
1386 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1387 dismissLoadingDialog();
1389 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1393 if (result
.isSuccess()) {
1394 OCFile removedFile
= operation
.getFile();
1395 FileFragment second
= getSecondFragment();
1396 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1397 if (second
instanceof PreviewMediaFragment
) {
1398 ((PreviewMediaFragment
)second
).stopPreview(true
);
1400 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1401 cleanSecondFragment();
1403 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1404 refreshListOfFilesFragment();
1406 invalidateOptionsMenu();
1408 if (result
.isSslRecoverableException()) {
1409 mLastSslUntrustedServerResult
= result
;
1410 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1417 * Updates the view associated to the activity after the finish of an operation trying to move a
1420 * @param operation Move operation performed.
1421 * @param result Result of the move operation.
1423 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1424 if (result
.isSuccess()) {
1425 dismissLoadingDialog();
1426 refreshListOfFilesFragment();
1428 dismissLoadingDialog();
1430 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1431 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1435 } catch (NotFoundException e
) {
1436 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1443 * Updates the view associated to the activity after the finish of an operation trying to rename a
1446 * @param operation Renaming operation performed.
1447 * @param result Result of the renaming.
1449 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1450 dismissLoadingDialog();
1451 OCFile renamedFile
= operation
.getFile();
1452 if (result
.isSuccess()) {
1453 FileFragment details
= getSecondFragment();
1454 if (details
!= null
) {
1455 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1456 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1457 showDetails(renamedFile
);
1459 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1460 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1461 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1462 int position
= ((PreviewMediaFragment
)details
).getPosition();
1463 startMediaPreview(renamedFile
, position
, true
);
1465 getFileOperationsHelper().openFile(renamedFile
);
1470 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1471 refreshListOfFilesFragment();
1475 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1479 if (result
.isSslRecoverableException()) {
1480 mLastSslUntrustedServerResult
= result
;
1481 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1486 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1487 dismissLoadingDialog();
1488 OCFile syncedFile
= operation
.getLocalFile();
1489 if (!result
.isSuccess()) {
1490 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1491 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1492 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1493 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1499 if (operation
.transferWasRequested()) {
1500 onTransferStateChanged(syncedFile
, true
, true
);
1503 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1511 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1513 * @param operation Creation operation performed.
1514 * @param result Result of the creation.
1516 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1517 if (result
.isSuccess()) {
1518 dismissLoadingDialog();
1519 refreshListOfFilesFragment();
1521 dismissLoadingDialog();
1523 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1524 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1528 } catch (NotFoundException e
) {
1529 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1539 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1540 refreshListOfFilesFragment();
1541 FileFragment details
= getSecondFragment();
1542 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1543 if (downloading
|| uploading
) {
1544 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1546 if (!file
.fileExists()) {
1547 cleanSecondFragment();
1549 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1557 private void requestForDownload() {
1558 Account account
= getAccount();
1559 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1560 Intent i
= new Intent(this, FileDownloader
.class);
1561 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1562 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1568 private OCFile
getCurrentDir() {
1569 OCFile file
= getFile();
1571 if (file
.isFolder()) {
1573 } else if (getStorageManager() != null
) {
1574 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1575 return getStorageManager().getFileByPath(parentPath
);
1581 public void startSyncFolderOperation(OCFile folder
) {
1582 long currentSyncTime
= System
.currentTimeMillis();
1584 mSyncInProgress
= true
;
1586 // perform folder synchronization
1587 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1590 getFileOperationsHelper().isSharedSupported(),
1591 getStorageManager(),
1593 getApplicationContext()
1595 synchFolderOp
.execute(getAccount(), this, null
, null
);
1597 setSupportProgressBarIndeterminateVisibility(true
);
1599 setBackgroundText();
1603 * Show untrusted cert dialog
1605 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1606 // Show a dialog with the certificate info
1607 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1608 FragmentManager fm
= getSupportFragmentManager();
1609 FragmentTransaction ft
= fm
.beginTransaction();
1610 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1613 private void requestForDownload(OCFile file
) {
1614 Account account
= getAccount();
1615 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1616 Intent i
= new Intent(this, FileDownloader
.class);
1617 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1618 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1623 private void sendDownloadedFile(){
1624 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1625 mWaitingToSend
= null
;
1630 * Requests the download of the received {@link OCFile} , updates the UI
1631 * to monitor the download progress and prepares the activity to send the file
1632 * when the download finishes.
1634 * @param file {@link OCFile} to download and preview.
1636 public void startDownloadForSending(OCFile file
) {
1637 mWaitingToSend
= file
;
1638 requestForDownload(mWaitingToSend
);
1639 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1640 updateFragmentsVisibility(hasSecondFragment
);
1644 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1646 * @param file Image {@link OCFile} to show.
1648 public void startImagePreview(OCFile file
) {
1649 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1650 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1651 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1652 startActivity(showDetailsIntent
);
1657 * Stars the preview of an already down media {@link OCFile}.
1659 * @param file Media {@link OCFile} to preview.
1660 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1661 * @param autoplay When 'true', the playback will start without user interactions.
1663 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1664 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1665 setSecondFragment(mediaFragment
);
1666 updateFragmentsVisibility(true
);
1667 updateNavigationElementsInActionBar(file
);
1672 * Requests the download of the received {@link OCFile} , updates the UI
1673 * to monitor the download progress and prepares the activity to preview
1674 * or open the file when the download finishes.
1676 * @param file {@link OCFile} to download and preview.
1678 public void startDownloadForPreview(OCFile file
) {
1679 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1680 setSecondFragment(detailFragment
);
1681 mWaitingToPreview
= file
;
1682 requestForDownload();
1683 updateFragmentsVisibility(true
);
1684 updateNavigationElementsInActionBar(file
);
1689 public void cancelTransference(OCFile file
) {
1690 getFileOperationsHelper().cancelTransference(file
);
1691 if (mWaitingToPreview
!= null
&&
1692 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1693 mWaitingToPreview
= null
;
1695 if (mWaitingToSend
!= null
&&
1696 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1697 mWaitingToSend
= null
;
1699 onTransferStateChanged(file
, false
, false
);
1703 public void onRefresh() {
1704 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1705 if (listOfFiles
!= null
) {
1706 OCFile folder
= listOfFiles
.getCurrentFile();
1707 if (folder
!= null
) {
1708 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1709 listDirectory(mFile);*/
1710 startSyncFolderOperation(folder
);