1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 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
;
23 import android
.accounts
.Account
;
24 import android
.app
.AlertDialog
;
25 import android
.app
.Dialog
;
26 import android
.app
.ProgressDialog
;
27 import android
.content
.BroadcastReceiver
;
28 import android
.content
.ComponentName
;
29 import android
.content
.ContentResolver
;
30 import android
.content
.Context
;
31 import android
.content
.DialogInterface
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.content
.SyncRequest
;
37 import android
.content
.res
.Resources
.NotFoundException
;
38 import android
.database
.Cursor
;
39 import android
.net
.Uri
;
40 import android
.os
.Bundle
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.provider
.MediaStore
;
44 import android
.support
.v4
.app
.Fragment
;
45 import android
.support
.v4
.app
.FragmentTransaction
;
46 import android
.support
.v4
.content
.LocalBroadcastManager
;
47 import android
.util
.Log
;
48 import android
.view
.View
;
49 import android
.view
.ViewGroup
;
50 import android
.widget
.ArrayAdapter
;
51 import android
.widget
.TextView
;
52 import android
.widget
.Toast
;
54 import com
.actionbarsherlock
.app
.ActionBar
;
55 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
56 import com
.actionbarsherlock
.view
.Menu
;
57 import com
.actionbarsherlock
.view
.MenuInflater
;
58 import com
.actionbarsherlock
.view
.MenuItem
;
59 import com
.actionbarsherlock
.view
.Window
;
60 import com
.owncloud
.android
.MainApp
;
61 import com
.owncloud
.android
.R
;
62 import com
.owncloud
.android
.datamodel
.OCFile
;
63 import com
.owncloud
.android
.files
.services
.FileDownloader
;
64 import com
.owncloud
.android
.files
.services
.FileObserverService
;
65 import com
.owncloud
.android
.files
.services
.FileUploader
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
67 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
68 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
70 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
71 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
72 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
.ResultCode
;
73 import com
.owncloud
.android
.operations
.CreateShareOperation
;
74 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
75 import com
.owncloud
.android
.operations
.RenameFileOperation
;
76 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
77 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
78 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
79 import com
.owncloud
.android
.services
.OperationsService
;
80 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
81 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
82 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
83 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
85 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
86 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
87 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
88 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
89 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
90 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
91 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
92 import com
.owncloud
.android
.utils
.DisplayUtils
;
93 import com
.owncloud
.android
.utils
.Log_OC
;
97 * Displays, what files the user has available in his ownCloud.
99 * @author Bartek Przybylski
100 * @author David A. Velasco
103 public class FileDisplayActivity
extends FileActivity
implements
104 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, EditNameDialogListener
{
106 private ArrayAdapter
<String
> mDirectories
;
108 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
109 private UploadFinishReceiver mUploadFinishReceiver
;
110 private DownloadFinishReceiver mDownloadFinishReceiver
;
111 private OperationsServiceReceiver mOperationsServiceReceiver
;
112 private FileDownloaderBinder mDownloaderBinder
= null
;
113 private FileUploaderBinder mUploaderBinder
= null
;
114 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
115 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
117 private boolean mDualPane
;
118 private View mLeftFragmentContainer
;
119 private View mRightFragmentContainer
;
121 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
122 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
123 private static final String KEY_REFRESH_SHARES_IN_PROGRESS
= "SHARES_IN_PROGRESS";
125 public static final int DIALOG_SHORT_WAIT
= 0;
126 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
127 private static final int DIALOG_SSL_VALIDATOR
= 2;
128 private static final int DIALOG_CERT_NOT_SAVED
= 3;
130 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
132 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
133 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
135 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
137 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
138 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
140 private OCFile mWaitingToPreview
;
142 private boolean mSyncInProgress
= false
;
143 private boolean mRefreshSharesInProgress
= false
;
146 protected void onCreate(Bundle savedInstanceState
) {
147 Log_OC
.d(TAG
, "onCreate() start");
148 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
150 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
152 /// bindings to transference services
153 mUploadConnection
= new ListServiceConnection();
154 mDownloadConnection
= new ListServiceConnection();
155 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
156 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
158 // PIN CODE request ; best location is to decide, let's try this first
159 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
161 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
166 Intent observer_intent
= new Intent(this, FileObserverService
.class);
167 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
168 startService(observer_intent
);
170 /// Load of saved instance state
171 if(savedInstanceState
!= null
) {
172 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
173 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
174 mRefreshSharesInProgress
= savedInstanceState
.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS
);
177 mWaitingToPreview
= null
;
178 mSyncInProgress
= false
;
179 mRefreshSharesInProgress
= false
;
184 // Inflate and set the layout view
185 setContentView(R
.layout
.files
);
186 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
187 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
188 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
189 if (savedInstanceState
== null
) {
190 createMinFragments();
194 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
195 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
196 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
|| mRefreshSharesInProgress
); // always AFTER setContentView(...) ; to work around bug in its implementation
198 Log_OC
.d(TAG
, "onCreate() end");
202 protected void onStart() {
204 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
208 protected void onDestroy() {
210 if (mDownloadConnection
!= null
)
211 unbindService(mDownloadConnection
);
212 if (mUploadConnection
!= null
)
213 unbindService(mUploadConnection
);
218 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
221 protected void onAccountSet(boolean stateWasRecovered
) {
222 super.onAccountSet(stateWasRecovered
);
223 if (getAccount() != null
) {
224 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
225 OCFile file
= getFile();
226 // get parent from path
227 String parentPath
= "";
229 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
230 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
231 // get parent from path
232 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
233 if (getStorageManager().getFileByPath(parentPath
) == null
)
234 file
= null
; // not able to know the directory where the file is uploading
236 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
240 // fall back to root folder
241 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
244 setNavigationListWithFolder(file
);
246 if (!stateWasRecovered
) {
247 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
248 initFragmentsWithFile();
249 if (file
.isFolder()) {
250 startSyncFolderOperation(file
);
254 updateFragmentsVisibility(!file
.isFolder());
255 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
261 private void setNavigationListWithFolder(OCFile file
) {
262 mDirectories
.clear();
263 OCFile fileIt
= file
;
265 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
266 if (fileIt
.isFolder()) {
267 mDirectories
.add(fileIt
.getFileName());
269 // get parent from path
270 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
271 fileIt
= getStorageManager().getFileByPath(parentPath
);
273 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
277 private void createMinFragments() {
278 OCFileListFragment listOfFiles
= new OCFileListFragment();
279 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
280 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
281 transaction
.commit();
284 private void initFragmentsWithFile() {
285 if (getAccount() != null
&& getFile() != null
) {
287 OCFileListFragment listOfFiles
= getListOfFilesFragment();
288 if (listOfFiles
!= null
) {
289 listOfFiles
.listDirectory(getCurrentDir());
291 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
295 OCFile file
= getFile();
296 Fragment secondFragment
= chooseInitialSecondFragment(file
);
297 if (secondFragment
!= null
) {
298 setSecondFragment(secondFragment
);
299 updateFragmentsVisibility(true
);
300 updateNavigationElementsInActionBar(file
);
303 cleanSecondFragment();
307 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
308 if (getAccount() == null
) {
309 Log
.wtf(TAG
, "\t account is NULL");
311 if (getFile() == null
) {
312 Log
.wtf(TAG
, "\t file is NULL");
317 private Fragment
chooseInitialSecondFragment(OCFile file
) {
318 Fragment secondFragment
= null
;
319 if (file
!= null
&& !file
.isFolder()) {
320 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
321 && file
.getLastSyncDateForProperties() > 0 // temporal fix
323 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
324 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
325 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
328 secondFragment
= new FileDetailFragment(file
, getAccount());
331 return secondFragment
;
336 * Replaces the second fragment managed by the activity with the received as
339 * Assumes never will be more than two fragments managed at the same time.
341 * @param fragment New second Fragment to set.
343 private void setSecondFragment(Fragment fragment
) {
344 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
345 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
346 transaction
.commit();
350 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
352 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
353 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
355 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
356 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
359 } else if (existsSecondFragment
) {
360 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
361 mLeftFragmentContainer
.setVisibility(View
.GONE
);
363 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
368 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
371 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
372 mRightFragmentContainer
.setVisibility(View
.GONE
);
378 private OCFileListFragment
getListOfFilesFragment() {
379 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
380 if (listOfFiles
!= null
) {
381 return (OCFileListFragment
)listOfFiles
;
383 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
387 protected FileFragment
getSecondFragment() {
388 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
389 if (second
!= null
) {
390 return (FileFragment
)second
;
395 public void cleanSecondFragment() {
396 Fragment second
= getSecondFragment();
397 if (second
!= null
) {
398 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
402 updateFragmentsVisibility(false
);
403 updateNavigationElementsInActionBar(null
);
406 protected void refeshListOfFilesFragment() {
407 OCFileListFragment fileListFragment
= getListOfFilesFragment();
408 if (fileListFragment
!= null
) {
409 fileListFragment
.listDirectory();
413 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
414 FileFragment secondFragment
= getSecondFragment();
415 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
416 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
417 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
418 OCFile fileInFragment
= detailsFragment
.getFile();
419 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
420 // the user browsed to other file ; forget the automatic preview
421 mWaitingToPreview
= null
;
423 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
424 // grant that the right panel updates the progress bar
425 detailsFragment
.listenForTransferProgress();
426 detailsFragment
.updateFileDetails(true
, false
);
428 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
429 // update the right panel
430 boolean detailsFragmentChanged
= false
;
433 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
434 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
435 startMediaPreview(mWaitingToPreview
, 0, true
);
436 detailsFragmentChanged
= true
;
438 getFileOperationsHelper().openFile(mWaitingToPreview
, this);
441 mWaitingToPreview
= null
;
443 if (!detailsFragmentChanged
) {
444 detailsFragment
.updateFileDetails(false
, (success
));
451 public boolean onCreateOptionsMenu(Menu menu
) {
452 MenuInflater inflater
= getSherlock().getMenuInflater();
453 inflater
.inflate(R
.menu
.main_menu
, menu
);
458 public boolean onOptionsItemSelected(MenuItem item
) {
459 boolean retval
= true
;
460 switch (item
.getItemId()) {
461 case R
.id
.action_create_dir
: {
462 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
463 dialog
.show(getSupportFragmentManager(), "createdirdialog");
466 case R
.id
.action_sync_account
: {
467 startSynchronization();
470 case R
.id
.action_upload
: {
471 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
474 case R
.id
.action_settings
: {
475 Intent settingsIntent
= new Intent(this, Preferences
.class);
476 startActivity(settingsIntent
);
479 case android
.R
.id
.home
: {
480 FileFragment second
= getSecondFragment();
481 OCFile currentDir
= getCurrentDir();
482 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
483 (second
!= null
&& second
.getFile() != null
)) {
490 retval
= super.onOptionsItemSelected(item
);
495 private void startSynchronization() {
496 Log_OC
.e(TAG
, "Got to start sync");
497 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
498 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
499 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
500 Bundle bundle
= new Bundle();
501 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
502 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
503 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
504 ContentResolver
.requestSync(
506 MainApp
.getAuthority(), bundle
);
508 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
509 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
510 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
511 builder
.setExpedited(true
);
512 builder
.setManual(true
);
514 SyncRequest request
= builder
.build();
515 ContentResolver
.requestSync(request
);
521 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
522 if (itemPosition
!= 0) {
523 String targetPath
= "";
524 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
525 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
527 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
528 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
529 if (targetFolder
!= null
) {
530 browseTo(targetFolder
);
533 // the next operation triggers a new call to this method, but it's necessary to
534 // ensure that the name exposed in the action bar is the current directory when the
535 // user selected it in the navigation list
536 getSupportActionBar().setSelectedNavigationItem(0);
542 * Called, when the user selected something for uploading
544 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
545 super.onActivityResult(requestCode
, resultCode
, data
);
547 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
548 requestSimpleUpload(data
, resultCode
);
550 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
551 requestMultipleUpload(data
, resultCode
);
556 private void requestMultipleUpload(Intent data
, int resultCode
) {
557 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
558 if (filePaths
!= null
) {
559 String
[] remotePaths
= new String
[filePaths
.length
];
560 String remotePathBase
= "";
561 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
562 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
564 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
565 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
566 for (int j
= 0; j
< remotePaths
.length
; j
++) {
567 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
570 Intent i
= new Intent(this, FileUploader
.class);
571 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
572 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
573 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
574 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
575 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
576 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
580 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
581 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
588 private void requestSimpleUpload(Intent data
, int resultCode
) {
589 String filepath
= null
;
591 Uri selectedImageUri
= data
.getData();
593 String filemanagerstring
= selectedImageUri
.getPath();
594 String selectedImagePath
= getPath(selectedImageUri
);
596 if (selectedImagePath
!= null
)
597 filepath
= selectedImagePath
;
599 filepath
= filemanagerstring
;
601 } catch (Exception e
) {
602 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
606 if (filepath
== null
) {
607 Log_OC
.e(TAG
, "Couldnt resolve path to file");
608 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
614 Intent i
= new Intent(this, FileUploader
.class);
615 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
617 String remotepath
= new String();
618 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
619 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
621 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
622 remotepath
+= OCFile
.PATH_SEPARATOR
;
623 remotepath
+= new File(filepath
).getName();
625 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
626 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
627 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
628 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
629 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
634 public void onBackPressed() {
635 OCFileListFragment listOfFiles
= getListOfFilesFragment();
636 if (mDualPane
|| getSecondFragment() == null
) {
637 if (listOfFiles
!= null
) { // should never be null, indeed
638 if (mDirectories
.getCount() <= 1) {
642 int levelsUp
= listOfFiles
.onBrowseUp();
643 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
648 if (listOfFiles
!= null
) { // should never be null, indeed
649 setFile(listOfFiles
.getCurrentFile());
651 cleanSecondFragment();
656 protected void onSaveInstanceState(Bundle outState
) {
657 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
658 Log_OC
.e(TAG
, "onSaveInstanceState() start");
659 super.onSaveInstanceState(outState
);
660 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
661 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
662 outState
.putBoolean(FileDisplayActivity
.KEY_REFRESH_SHARES_IN_PROGRESS
, mRefreshSharesInProgress
);
664 Log_OC
.d(TAG
, "onSaveInstanceState() end");
670 protected void onResume() {
672 Log_OC
.e(TAG
, "onResume() start");
674 // Listen for sync messages
675 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
676 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
677 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FOLDER_SIZE_SYNCED
);
678 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FOLDER_CONTENTS_SYNCED
);
679 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SYNCED
);
680 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
681 //registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
682 LocalBroadcastManager
.getInstance(this).registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
684 // Listen for upload messages
685 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
686 mUploadFinishReceiver
= new UploadFinishReceiver();
687 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
689 // Listen for download messages
690 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
691 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
692 mDownloadFinishReceiver
= new DownloadFinishReceiver();
693 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
695 // Listen for messages from the OperationsService
696 IntentFilter operationsIntentFilter
= new IntentFilter(OperationsService
.ACTION_OPERATION_ADDED
);
697 operationsIntentFilter
.addAction(OperationsService
.ACTION_OPERATION_FINISHED
);
698 mOperationsServiceReceiver
= new OperationsServiceReceiver();
699 LocalBroadcastManager
.getInstance(this).registerReceiver(mOperationsServiceReceiver
, operationsIntentFilter
);
701 Log_OC
.d(TAG
, "onResume() end");
706 protected void onPause() {
708 Log_OC
.e(TAG
, "onPause() start");
709 if (mSyncBroadcastReceiver
!= null
) {
710 //unregisterReceiver(mSyncBroadcastReceiver);
711 LocalBroadcastManager
.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver
);
712 mSyncBroadcastReceiver
= null
;
714 if (mUploadFinishReceiver
!= null
) {
715 unregisterReceiver(mUploadFinishReceiver
);
716 mUploadFinishReceiver
= null
;
718 if (mDownloadFinishReceiver
!= null
) {
719 unregisterReceiver(mDownloadFinishReceiver
);
720 mDownloadFinishReceiver
= null
;
722 if (mOperationsServiceReceiver
!= null
) {
723 LocalBroadcastManager
.getInstance(this).unregisterReceiver(mOperationsServiceReceiver
);
724 mOperationsServiceReceiver
= null
;
726 Log_OC
.d(TAG
, "onPause() end");
731 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
732 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
733 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
739 protected Dialog
onCreateDialog(int id
) {
740 Dialog dialog
= null
;
741 AlertDialog
.Builder builder
;
743 case DIALOG_SHORT_WAIT
: {
744 ProgressDialog working_dialog
= new ProgressDialog(this);
745 working_dialog
.setMessage(getResources().getString(
746 R
.string
.wait_a_moment
));
747 working_dialog
.setIndeterminate(true
);
748 working_dialog
.setCancelable(false
);
749 dialog
= working_dialog
;
752 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
754 String
[] items
= null
;
756 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
757 getString(R
.string
.actionbar_upload_from_apps
),
758 getString(R
.string
.actionbar_failed_instant_upload
) };
760 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
761 getString(R
.string
.actionbar_upload_from_apps
) };
763 if (InstantUploadActivity
.IS_ENABLED
)
768 builder
= new AlertDialog
.Builder(this);
769 builder
.setTitle(R
.string
.actionbar_upload
);
770 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
771 public void onClick(DialogInterface dialog
, int item
) {
774 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
775 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
776 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
778 // TODO create and handle new fragment
779 // LocalFileListFragment
781 } else if (item
== 1) {
782 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
783 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
784 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
785 ACTION_SELECT_CONTENT_FROM_APPS
);
786 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
787 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
788 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
789 startActivity(action
);
793 dialog
= builder
.create();
796 case DIALOG_SSL_VALIDATOR
: {
797 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
800 case DIALOG_CERT_NOT_SAVED
: {
801 builder
= new AlertDialog
.Builder(this);
802 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
803 builder
.setCancelable(false
);
804 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
806 public void onClick(DialogInterface dialog
, int which
) {
810 dialog
= builder
.create();
822 * Translates a content URI of an image to a physical path
824 * @param uri The URI to resolve
825 * @return The path to the image or null if it could not be found
827 public String
getPath(Uri uri
) {
828 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
829 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
830 if (cursor
!= null
) {
831 int column_index
= cursor
832 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
833 cursor
.moveToFirst();
834 return cursor
.getString(column_index
);
840 * Pushes a directory to the drop down list
841 * @param directory to push
842 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
844 public void pushDirname(OCFile directory
) {
845 if(!directory
.isFolder()){
846 throw new IllegalArgumentException("Only directories may be pushed!");
848 mDirectories
.insert(directory
.getFileName(), 0);
853 * Pops a directory name from the drop down list
854 * @return True, unless the stack is empty
856 public boolean popDirname() {
857 mDirectories
.remove(mDirectories
.getItem(0));
858 return !mDirectories
.isEmpty();
861 // Custom array adapter to override text colors
862 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
864 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
868 public View
getView(int position
, View convertView
, ViewGroup parent
) {
869 View v
= super.getView(position
, convertView
, parent
);
871 ((TextView
) v
).setTextColor(getResources().getColorStateList(
872 android
.R
.color
.white
));
876 public View
getDropDownView(int position
, View convertView
,
878 View v
= super.getDropDownView(position
, convertView
, parent
);
880 ((TextView
) v
).setTextColor(getResources().getColorStateList(
881 android
.R
.color
.white
));
888 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
891 * {@link BroadcastReceiver} to enable syncing feedback in UI
894 public void onReceive(Context context
, Intent intent
) {
895 String event
= intent
.getAction();
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 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
905 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
907 if (currentDir
== null
) {
908 // current folder was removed from the server
909 Toast
.makeText( FileDisplayActivity
.this,
910 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
916 if (currentFile
== null
&& !getFile().isFolder()) {
917 // currently selected file was removed in the server, and now we know it
918 cleanSecondFragment();
919 currentFile
= currentDir
;
922 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
923 OCFileListFragment fileListFragment
= getListOfFilesFragment();
924 if (fileListFragment
!= null
) {
925 fileListFragment
.listDirectory(currentDir
);
928 setFile(currentFile
);
931 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
932 !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SYNCED
.equals(event
) &&
933 (synchResult
== null
|| synchResult
.isSuccess())) ;
935 if (synchResult
!= null
&&
936 synchResult
.isSuccess() &&
937 (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SYNCED
.equals(event
) ||
938 FileSyncAdapter
.EVENT_FOLDER_CONTENTS_SYNCED
.equals(event
)
940 !mRefreshSharesInProgress
&&
941 getFileOperationsHelper().isSharedSupported(FileDisplayActivity
.this)
947 //removeStickyBroadcast(intent);
948 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
|| mRefreshSharesInProgress
);
951 if (synchResult
!= null
) {
952 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
953 mLastSslUntrustedServerResult
= synchResult
;
954 showDialog(DIALOG_SSL_VALIDATOR
);
961 private class UploadFinishReceiver
extends BroadcastReceiver
{
963 * Once the file upload has finished -> update view
964 * @author David A. Velasco
965 * {@link BroadcastReceiver} to enable upload feedback in UI
968 public void onReceive(Context context
, Intent intent
) {
969 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
970 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
971 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
972 OCFile currentDir
= getCurrentDir();
973 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
974 if (sameAccount
&& isDescendant
) {
975 refeshListOfFilesFragment();
983 * Class waiting for broadcast events from the {@link FielDownloader} service.
985 * Updates the UI when a download is started or finished, provided that it is relevant for the
988 private class DownloadFinishReceiver
extends BroadcastReceiver
{
990 public void onReceive(Context context
, Intent intent
) {
991 boolean sameAccount
= isSameAccount(context
, intent
);
992 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
993 boolean isDescendant
= isDescendant(downloadedRemotePath
);
995 if (sameAccount
&& isDescendant
) {
996 refeshListOfFilesFragment();
997 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1000 removeStickyBroadcast(intent
);
1003 private boolean isDescendant(String downloadedRemotePath
) {
1004 OCFile currentDir
= getCurrentDir();
1005 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1008 private boolean isSameAccount(Context context
, Intent intent
) {
1009 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1010 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1016 * Class waiting for broadcast events from the {@link OperationsService}.
1018 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1019 * operation performed in {@link OperationsService}.
1021 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1022 * probably all the operations associated to the app model.
1024 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1027 public void onReceive(Context context
, Intent intent
) {
1028 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1030 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1031 mRefreshSharesInProgress
= false
;
1033 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1034 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1035 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1036 && getStorageManager() != null
1038 refeshListOfFilesFragment();
1040 if ((getSharesResult
!= null
) &&
1041 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1042 mLastSslUntrustedServerResult
= getSharesResult
;
1043 showDialog(DIALOG_SSL_VALIDATOR
);
1046 setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress
|| mSyncInProgress
);
1053 public void browseToRoot() {
1054 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1055 if (listOfFiles
!= null
) { // should never be null, indeed
1056 while (mDirectories
.getCount() > 1) {
1059 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1060 listOfFiles
.listDirectory(root
);
1061 setFile(listOfFiles
.getCurrentFile());
1062 startSyncFolderOperation(root
);
1064 cleanSecondFragment();
1068 public void browseTo(OCFile folder
) {
1069 if (folder
== null
|| !folder
.isFolder()) {
1070 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1072 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1073 if (listOfFiles
!= null
) {
1074 setNavigationListWithFolder(folder
);
1075 listOfFiles
.listDirectory(folder
);
1076 setFile(listOfFiles
.getCurrentFile());
1077 startSyncFolderOperation(folder
);
1079 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1081 cleanSecondFragment();
1088 * Updates action bar and second fragment, if in dual pane mode.
1091 public void onBrowsedDownTo(OCFile directory
) {
1092 pushDirname(directory
);
1093 cleanSecondFragment();
1096 startSyncFolderOperation(directory
);
1101 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1103 * @param file Image {@link OCFile} to show.
1106 public void startImagePreview(OCFile file
) {
1107 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1108 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1109 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1110 startActivity(showDetailsIntent
);
1114 * Stars the preview of an already down media {@link OCFile}.
1116 * @param file Media {@link OCFile} to preview.
1117 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1118 * @param autoplay When 'true', the playback will start without user interactions.
1121 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1122 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1123 setSecondFragment(mediaFragment
);
1124 updateFragmentsVisibility(true
);
1125 updateNavigationElementsInActionBar(file
);
1130 * Requests the download of the received {@link OCFile} , updates the UI
1131 * to monitor the download progress and prepares the activity to preview
1132 * or open the file when the download finishes.
1134 * @param file {@link OCFile} to download and preview.
1137 public void startDownloadForPreview(OCFile file
) {
1138 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1139 setSecondFragment(detailFragment
);
1140 mWaitingToPreview
= file
;
1141 requestForDownload();
1142 updateFragmentsVisibility(true
);
1143 updateNavigationElementsInActionBar(file
);
1149 * Shows the information of the {@link OCFile} received as a
1150 * parameter in the second fragment.
1152 * @param file {@link OCFile} whose details will be shown
1155 public void showDetails(OCFile file
) {
1156 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1157 setSecondFragment(detailFragment
);
1158 updateFragmentsVisibility(true
);
1159 updateNavigationElementsInActionBar(file
);
1167 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1168 ActionBar actionBar
= getSupportActionBar();
1169 if (chosenFile
== null
|| mDualPane
) {
1170 // only list of files - set for browsing through folders
1171 OCFile currentDir
= getCurrentDir();
1172 actionBar
.setDisplayHomeAsUpEnabled(currentDir
!= null
&& currentDir
.getParentId() != 0);
1173 actionBar
.setDisplayShowTitleEnabled(false
);
1174 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
1175 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1178 actionBar
.setDisplayHomeAsUpEnabled(true
);
1179 actionBar
.setDisplayShowTitleEnabled(true
);
1180 actionBar
.setTitle(chosenFile
.getFileName());
1181 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1190 public void onFileStateChanged() {
1191 refeshListOfFilesFragment();
1192 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1200 public FileDownloaderBinder
getFileDownloaderBinder() {
1201 return mDownloaderBinder
;
1209 public FileUploaderBinder
getFileUploaderBinder() {
1210 return mUploaderBinder
;
1214 /** Defines callbacks for service binding, passed to bindService() */
1215 private class ListServiceConnection
implements ServiceConnection
{
1218 public void onServiceConnected(ComponentName component
, IBinder service
) {
1219 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1220 Log_OC
.d(TAG
, "Download service connected");
1221 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1222 if (mWaitingToPreview
!= null
) {
1223 requestForDownload();
1226 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1227 Log_OC
.d(TAG
, "Upload service connected");
1228 mUploaderBinder
= (FileUploaderBinder
) service
;
1232 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1233 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1234 if (listOfFiles
!= null
) {
1235 listOfFiles
.listDirectory();
1237 FileFragment secondFragment
= getSecondFragment();
1238 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1239 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1240 detailFragment
.listenForTransferProgress();
1241 detailFragment
.updateFileDetails(false
, false
);
1246 public void onServiceDisconnected(ComponentName component
) {
1247 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1248 Log_OC
.d(TAG
, "Download service disconnected");
1249 mDownloaderBinder
= null
;
1250 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1251 Log_OC
.d(TAG
, "Upload service disconnected");
1252 mUploaderBinder
= null
;
1260 * Launch an intent to request the PIN code to the user before letting him use the app
1262 private void requestPinCode() {
1263 boolean pinStart
= false
;
1264 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1265 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1267 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1268 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1275 public void onSavedCertificate() {
1276 startSyncFolderOperation(getCurrentDir());
1281 public void onFailedSavingCertificate() {
1282 showDialog(DIALOG_CERT_NOT_SAVED
);
1287 * Updates the view associated to the activity after the finish of some operation over files
1288 * in the current account.
1290 * @param operation Removal operation performed.
1291 * @param result Result of the removal.
1294 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1295 super.onRemoteOperationFinish(operation
, result
);
1297 if (operation
instanceof RemoveFileOperation
) {
1298 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1300 } else if (operation
instanceof RenameFileOperation
) {
1301 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1303 } else if (operation
instanceof SynchronizeFileOperation
) {
1304 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1306 } else if (operation
instanceof CreateFolderOperation
) {
1307 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1309 } else if (operation
instanceof CreateShareOperation
) {
1310 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1312 } else if (operation
instanceof UnshareLinkOperation
) {
1313 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1320 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1321 if (result
.isSuccess()) {
1322 refreshShowDetails();
1323 refeshListOfFilesFragment();
1328 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1329 if (result
.isSuccess()) {
1330 refreshShowDetails();
1331 refeshListOfFilesFragment();
1335 private void refreshShowDetails() {
1336 FileFragment details
= getSecondFragment();
1337 if (details
!= null
) {
1338 OCFile file
= details
.getFile();
1340 file
= getStorageManager().getFileByPath(file
.getRemotePath()); {
1341 if (!(details
instanceof PreviewMediaFragment
|| details
instanceof PreviewImageFragment
)) {
1343 } else if (details
instanceof PreviewMediaFragment
) {
1344 startMediaPreview(file
, 0, false
);
1347 invalidateOptionsMenu();
1353 * Updates the view associated to the activity after the finish of an operation trying to remove a
1356 * @param operation Removal operation performed.
1357 * @param result Result of the removal.
1359 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1360 dismissLoadingDialog();
1361 if (result
.isSuccess()) {
1362 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1364 OCFile removedFile
= operation
.getFile();
1365 getSecondFragment();
1366 FileFragment second
= getSecondFragment();
1367 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1368 cleanSecondFragment();
1370 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1371 refeshListOfFilesFragment();
1375 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1377 if (result
.isSslRecoverableException()) {
1378 mLastSslUntrustedServerResult
= result
;
1379 showDialog(DIALOG_SSL_VALIDATOR
);
1385 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1387 * @param operation Creation operation performed.
1388 * @param result Result of the creation.
1390 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1391 if (result
.isSuccess()) {
1392 dismissLoadingDialog();
1393 refeshListOfFilesFragment();
1396 dismissLoadingDialog();
1397 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1398 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1401 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1404 } catch (NotFoundException e
) {
1405 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1413 * Updates the view associated to the activity after the finish of an operation trying to rename a
1416 * @param operation Renaming operation performed.
1417 * @param result Result of the renaming.
1419 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1420 dismissLoadingDialog();
1421 OCFile renamedFile
= operation
.getFile();
1422 if (result
.isSuccess()) {
1424 FileFragment details
= getSecondFragment();
1425 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1426 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1429 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1430 refeshListOfFilesFragment();
1434 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1435 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1437 // TODO throw again the new rename dialog
1438 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1439 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1442 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1444 if (result
.isSslRecoverableException()) {
1445 mLastSslUntrustedServerResult
= result
;
1446 showDialog(DIALOG_SSL_VALIDATOR
);
1453 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1454 dismissLoadingDialog();
1455 OCFile syncedFile
= operation
.getLocalFile();
1456 if (!result
.isSuccess()) {
1457 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1458 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1459 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1460 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1466 if (operation
.transferWasRequested()) {
1467 refeshListOfFilesFragment();
1468 onTransferStateChanged(syncedFile
, true
, true
);
1471 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1482 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1484 FileFragment details
= getSecondFragment();
1485 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1486 if (downloading
|| uploading
) {
1487 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1489 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1496 public void onDismiss(EditNameDialog dialog
) {
1497 if (dialog
.getResult()) {
1498 String newDirectoryName
= dialog
.getNewFilename().trim();
1499 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1500 if (newDirectoryName
.length() > 0) {
1501 String path
= getCurrentDir().getRemotePath();
1504 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1505 RemoteOperation operation
= new CreateFolderOperation(path
, false
, getStorageManager());
1506 operation
.execute( getAccount(),
1507 FileDisplayActivity
.this,
1508 FileDisplayActivity
.this,
1510 FileDisplayActivity
.this);
1512 showLoadingDialog();
1518 private void requestForDownload() {
1519 Account account
= getAccount();
1520 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1521 Intent i
= new Intent(this, FileDownloader
.class);
1522 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1523 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1529 private OCFile
getCurrentDir() {
1530 OCFile file
= getFile();
1532 if (file
.isFolder()) {
1534 } else if (getStorageManager() != null
) {
1535 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1536 return getStorageManager().getFileByPath(parentPath
);
1542 public void startSyncFolderOperation(OCFile folder
) {
1543 long currentSyncTime
= System
.currentTimeMillis();
1545 mSyncInProgress
= true
;
1547 // perform folder synchronization
1548 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1551 getStorageManager(),
1553 getApplicationContext()
1555 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1557 setSupportProgressBarIndeterminateVisibility(true
);
1561 private void startGetShares() {
1562 // Get shared files/folders
1563 Intent intent
= new Intent(this, OperationsService
.class);
1564 intent
.putExtra(OperationsService
.EXTRA_ACCOUNT
, getAccount());
1565 startService(intent
);
1567 mRefreshSharesInProgress
= true
;