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
.Handler
;
42 import android
.os
.IBinder
;
43 import android
.preference
.PreferenceManager
;
44 import android
.provider
.MediaStore
;
45 import android
.support
.v4
.app
.Fragment
;
46 import android
.support
.v4
.app
.FragmentManager
;
47 import android
.support
.v4
.app
.FragmentTransaction
;
48 import android
.support
.v4
.content
.LocalBroadcastManager
;
49 import android
.util
.Log
;
50 import android
.view
.View
;
51 import android
.view
.ViewGroup
;
52 import android
.widget
.ArrayAdapter
;
53 import android
.widget
.TextView
;
54 import android
.widget
.Toast
;
56 import com
.actionbarsherlock
.app
.ActionBar
;
57 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
58 import com
.actionbarsherlock
.view
.Menu
;
59 import com
.actionbarsherlock
.view
.MenuInflater
;
60 import com
.actionbarsherlock
.view
.MenuItem
;
61 import com
.actionbarsherlock
.view
.Window
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
;
67 import com
.owncloud
.android
.files
.services
.FileObserverService
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
71 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
73 import com
.owncloud
.android
.lib
.operations
.common
.OnRemoteOperationListener
;
74 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
75 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
76 import com
.owncloud
.android
.lib
.operations
.common
.ShareType
;
77 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.operations
.CreateShareOperation
;
80 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
81 import com
.owncloud
.android
.operations
.RenameFileOperation
;
82 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
83 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
84 import com
.owncloud
.android
.services
.OperationsService
;
85 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
86 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
87 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
88 import com
.owncloud
.android
.ui
.dialog
.LoadingDialog
;
89 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
91 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
92 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
93 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
94 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
96 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
97 import com
.owncloud
.android
.utils
.DisplayUtils
;
98 import com
.owncloud
.android
.utils
.Log_OC
;
102 * Displays, what files the user has available in his ownCloud.
104 * @author Bartek Przybylski
105 * @author David A. Velasco
108 public class FileDisplayActivity
extends FileActivity
implements
109 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, OnRemoteOperationListener
, EditNameDialogListener
{
111 private ArrayAdapter
<String
> mDirectories
;
113 /** Access point to the cached database for the current ownCloud {@link Account} */
114 private FileDataStorageManager mStorageManager
= null
;
116 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
117 private UploadFinishReceiver mUploadFinishReceiver
;
118 private DownloadFinishReceiver mDownloadFinishReceiver
;
119 private OperationsServiceReceiver mOperationsServiceReceiver
;
120 private FileDownloaderBinder mDownloaderBinder
= null
;
121 private FileUploaderBinder mUploaderBinder
= null
;
122 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
123 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
125 private boolean mDualPane
;
126 private View mLeftFragmentContainer
;
127 private View mRightFragmentContainer
;
129 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
130 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
131 private static final String KEY_REFRESH_SHARES_IN_PROGRESS
= "SHARES_IN_PROGRESS";
133 public static final int DIALOG_SHORT_WAIT
= 0;
134 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
135 private static final int DIALOG_SSL_VALIDATOR
= 2;
136 private static final int DIALOG_CERT_NOT_SAVED
= 3;
138 private static final String DIALOG_WAIT_TAG
= "DIALOG_WAIT";
140 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
142 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
143 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
145 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
147 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
148 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
150 private OCFile mWaitingToPreview
;
151 private Handler mHandler
;
153 private boolean mSyncInProgress
= false
;
154 private boolean mRefreshSharesInProgress
= false
;
157 protected void onCreate(Bundle savedInstanceState
) {
158 Log_OC
.d(TAG
, "onCreate() start");
159 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
161 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
163 mHandler
= new Handler();
165 /// bindings to transference services
166 mUploadConnection
= new ListServiceConnection();
167 mDownloadConnection
= new ListServiceConnection();
168 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
169 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
171 // PIN CODE request ; best location is to decide, let's try this first
172 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
174 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
179 Intent observer_intent
= new Intent(this, FileObserverService
.class);
180 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
181 startService(observer_intent
);
183 /// Load of saved instance state
184 if(savedInstanceState
!= null
) {
185 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
186 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
187 mRefreshSharesInProgress
= savedInstanceState
.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS
);
190 mWaitingToPreview
= null
;
191 mSyncInProgress
= false
;
192 mRefreshSharesInProgress
= false
;
197 // Inflate and set the layout view
198 setContentView(R
.layout
.files
);
199 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
200 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
201 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
202 if (savedInstanceState
== null
) {
203 createMinFragments();
207 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
208 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
209 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
); // always AFTER setContentView(...) ; to work around bug in its implementation
211 Log_OC
.d(TAG
, "onCreate() end");
215 protected void onStart() {
217 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
221 protected void onDestroy() {
223 if (mDownloadConnection
!= null
)
224 unbindService(mDownloadConnection
);
225 if (mUploadConnection
!= null
)
226 unbindService(mUploadConnection
);
231 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
234 protected void onAccountSet(boolean stateWasRecovered
) {
235 if (getAccount() != null
) {
236 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
238 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
239 OCFile file
= getFile();
240 // get parent from path
241 String parentPath
= "";
243 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
244 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
245 // get parent from path
246 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
247 if (mStorageManager
.getFileByPath(parentPath
) == null
)
248 file
= null
; // not able to know the directory where the file is uploading
250 file
= mStorageManager
.getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
254 // fall back to root folder
255 file
= mStorageManager
.getFileByPath(OCFile
.ROOT_PATH
); // never returns null
258 setNavigationListWithFolder(file
);
260 if (!stateWasRecovered
) {
261 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
262 initFragmentsWithFile();
263 if (file
.isFolder()) {
264 startSyncFolderOperation(file
);
268 updateFragmentsVisibility(!file
.isFolder());
269 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
274 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
279 private void setNavigationListWithFolder(OCFile file
) {
280 mDirectories
.clear();
281 OCFile fileIt
= file
;
283 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
284 if (fileIt
.isFolder()) {
285 mDirectories
.add(fileIt
.getFileName());
287 //fileIt = mStorageManager.getFileById(fileIt.getParentId());
288 // get parent from path
289 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
290 fileIt
= mStorageManager
.getFileByPath(parentPath
);
292 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
296 private void createMinFragments() {
297 OCFileListFragment listOfFiles
= new OCFileListFragment();
298 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
299 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
300 transaction
.commit();
303 private void initFragmentsWithFile() {
304 if (getAccount() != null
&& getFile() != null
) {
306 OCFileListFragment listOfFiles
= getListOfFilesFragment();
307 if (listOfFiles
!= null
) {
308 listOfFiles
.listDirectory(getCurrentDir());
310 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
314 OCFile file
= getFile();
315 Fragment secondFragment
= chooseInitialSecondFragment(file
);
316 if (secondFragment
!= null
) {
317 setSecondFragment(secondFragment
);
318 updateFragmentsVisibility(true
);
319 updateNavigationElementsInActionBar(file
);
322 cleanSecondFragment();
326 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
327 if (getAccount() == null
) {
328 Log
.wtf(TAG
, "\t account is NULL");
330 if (getFile() == null
) {
331 Log
.wtf(TAG
, "\t file is NULL");
336 private Fragment
chooseInitialSecondFragment(OCFile file
) {
337 Fragment secondFragment
= null
;
338 if (file
!= null
&& !file
.isFolder()) {
339 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
340 && file
.getLastSyncDateForProperties() > 0 // temporal fix
342 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
343 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
344 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
347 secondFragment
= new FileDetailFragment(file
, getAccount());
350 return secondFragment
;
355 * Replaces the second fragment managed by the activity with the received as
358 * Assumes never will be more than two fragments managed at the same time.
360 * @param fragment New second Fragment to set.
362 private void setSecondFragment(Fragment fragment
) {
363 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
364 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
365 transaction
.commit();
369 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
371 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
372 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
374 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
378 } else if (existsSecondFragment
) {
379 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
380 mLeftFragmentContainer
.setVisibility(View
.GONE
);
382 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
383 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
387 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
388 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
390 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
391 mRightFragmentContainer
.setVisibility(View
.GONE
);
397 private OCFileListFragment
getListOfFilesFragment() {
398 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
399 if (listOfFiles
!= null
) {
400 return (OCFileListFragment
)listOfFiles
;
402 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
406 protected FileFragment
getSecondFragment() {
407 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
408 if (second
!= null
) {
409 return (FileFragment
)second
;
414 public void cleanSecondFragment() {
415 Fragment second
= getSecondFragment();
416 if (second
!= null
) {
417 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
421 updateFragmentsVisibility(false
);
422 updateNavigationElementsInActionBar(null
);
425 protected void refeshListOfFilesFragment() {
426 OCFileListFragment fileListFragment
= getListOfFilesFragment();
427 if (fileListFragment
!= null
) {
428 fileListFragment
.listDirectory();
432 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
433 FileFragment secondFragment
= getSecondFragment();
434 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
435 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
436 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
437 OCFile fileInFragment
= detailsFragment
.getFile();
438 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
439 // the user browsed to other file ; forget the automatic preview
440 mWaitingToPreview
= null
;
442 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
443 // grant that the right panel updates the progress bar
444 detailsFragment
.listenForTransferProgress();
445 detailsFragment
.updateFileDetails(true
, false
);
447 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
448 // update the right panel
449 boolean detailsFragmentChanged
= false
;
452 mWaitingToPreview
= mStorageManager
.getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
453 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
454 startMediaPreview(mWaitingToPreview
, 0, true
);
455 detailsFragmentChanged
= true
;
457 openFile(mWaitingToPreview
);
460 mWaitingToPreview
= null
;
462 if (!detailsFragmentChanged
) {
463 detailsFragment
.updateFileDetails(false
, (success
));
471 public boolean onCreateOptionsMenu(Menu menu
) {
472 MenuInflater inflater
= getSherlock().getMenuInflater();
473 inflater
.inflate(R
.menu
.main_menu
, menu
);
478 public boolean onOptionsItemSelected(MenuItem item
) {
479 boolean retval
= true
;
480 switch (item
.getItemId()) {
481 case R
.id
.action_create_dir
: {
482 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
483 dialog
.show(getSupportFragmentManager(), "createdirdialog");
486 case R
.id
.action_sync_account
: {
487 startSynchronization();
490 case R
.id
.action_upload
: {
491 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
494 case R
.id
.action_settings
: {
495 Intent settingsIntent
= new Intent(this, Preferences
.class);
496 startActivity(settingsIntent
);
499 case android
.R
.id
.home
: {
500 FileFragment second
= getSecondFragment();
501 OCFile currentDir
= getCurrentDir();
502 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
503 (second
!= null
&& second
.getFile() != null
)) {
510 retval
= super.onOptionsItemSelected(item
);
515 private void startSynchronization() {
516 Log_OC
.e(TAG
, "Got to start sync");
517 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
518 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
519 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
520 Bundle bundle
= new Bundle();
521 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
522 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
523 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
524 ContentResolver
.requestSync(
526 MainApp
.getAuthority(), bundle
);
528 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
529 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
530 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
531 builder
.setExpedited(true
);
532 builder
.setManual(true
);
534 SyncRequest request
= builder
.build();
535 ContentResolver
.requestSync(request
);
541 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
542 if (itemPosition
!= 0) {
543 String targetPath
= "";
544 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
545 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
547 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
548 OCFile targetFolder
= mStorageManager
.getFileByPath(targetPath
);
549 if (targetFolder
!= null
) {
550 browseTo(targetFolder
);
553 // the next operation triggers a new call to this method, but it's necessary to
554 // ensure that the name exposed in the action bar is the current directory when the
555 // user selected it in the navigation list
556 getSupportActionBar().setSelectedNavigationItem(0);
562 * Called, when the user selected something for uploading
564 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
565 super.onActivityResult(requestCode
, resultCode
, data
);
567 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
568 requestSimpleUpload(data
, resultCode
);
570 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
571 requestMultipleUpload(data
, resultCode
);
576 private void requestMultipleUpload(Intent data
, int resultCode
) {
577 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
578 if (filePaths
!= null
) {
579 String
[] remotePaths
= new String
[filePaths
.length
];
580 String remotePathBase
= "";
581 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
582 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
584 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
585 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
586 for (int j
= 0; j
< remotePaths
.length
; j
++) {
587 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
590 Intent i
= new Intent(this, FileUploader
.class);
591 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
592 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
593 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
594 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
595 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
596 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
600 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
601 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
608 private void requestSimpleUpload(Intent data
, int resultCode
) {
609 String filepath
= null
;
611 Uri selectedImageUri
= data
.getData();
613 String filemanagerstring
= selectedImageUri
.getPath();
614 String selectedImagePath
= getPath(selectedImageUri
);
616 if (selectedImagePath
!= null
)
617 filepath
= selectedImagePath
;
619 filepath
= filemanagerstring
;
621 } catch (Exception e
) {
622 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
626 if (filepath
== null
) {
627 Log_OC
.e(TAG
, "Couldnt resolve path to file");
628 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
634 Intent i
= new Intent(this, FileUploader
.class);
635 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
637 String remotepath
= new String();
638 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
639 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
641 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
642 remotepath
+= OCFile
.PATH_SEPARATOR
;
643 remotepath
+= new File(filepath
).getName();
645 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
646 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
647 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
648 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
649 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
654 public void onBackPressed() {
655 OCFileListFragment listOfFiles
= getListOfFilesFragment();
656 if (mDualPane
|| getSecondFragment() == null
) {
657 if (listOfFiles
!= null
) { // should never be null, indeed
658 if (mDirectories
.getCount() <= 1) {
662 int levelsUp
= listOfFiles
.onBrowseUp();
663 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
668 if (listOfFiles
!= null
) { // should never be null, indeed
669 setFile(listOfFiles
.getCurrentFile());
671 cleanSecondFragment();
676 protected void onSaveInstanceState(Bundle outState
) {
677 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
678 Log_OC
.e(TAG
, "onSaveInstanceState() start");
679 super.onSaveInstanceState(outState
);
680 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
681 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
682 outState
.putBoolean(FileDisplayActivity
.KEY_REFRESH_SHARES_IN_PROGRESS
, mRefreshSharesInProgress
);
684 Log_OC
.d(TAG
, "onSaveInstanceState() end");
690 protected void onResume() {
692 Log_OC
.e(TAG
, "onResume() start");
694 // Listen for sync messages
695 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.getSyncMessage());
696 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
697 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
699 // Listen for upload messages
700 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
701 mUploadFinishReceiver
= new UploadFinishReceiver();
702 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
704 // Listen for download messages
705 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
706 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
707 mDownloadFinishReceiver
= new DownloadFinishReceiver();
708 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
710 // Listen for messages from the OperationsService
711 IntentFilter operationsIntentFilter
= new IntentFilter(OperationsService
.ACTION_OPERATION_ADDED
);
712 operationsIntentFilter
.addAction(OperationsService
.ACTION_OPERATION_FINISHED
);
713 mOperationsServiceReceiver
= new OperationsServiceReceiver();
714 LocalBroadcastManager
.getInstance(this).registerReceiver(mOperationsServiceReceiver
, operationsIntentFilter
);
716 Log_OC
.d(TAG
, "onResume() end");
721 protected void onPause() {
723 Log_OC
.e(TAG
, "onPause() start");
724 if (mSyncBroadcastReceiver
!= null
) {
725 unregisterReceiver(mSyncBroadcastReceiver
);
726 mSyncBroadcastReceiver
= null
;
728 if (mUploadFinishReceiver
!= null
) {
729 unregisterReceiver(mUploadFinishReceiver
);
730 mUploadFinishReceiver
= null
;
732 if (mDownloadFinishReceiver
!= null
) {
733 unregisterReceiver(mDownloadFinishReceiver
);
734 mDownloadFinishReceiver
= null
;
736 if (mOperationsServiceReceiver
!= null
) {
737 LocalBroadcastManager
.getInstance(this).unregisterReceiver(mOperationsServiceReceiver
);
738 mOperationsServiceReceiver
= null
;
740 Log_OC
.d(TAG
, "onPause() end");
745 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
746 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
747 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
753 protected Dialog
onCreateDialog(int id
) {
754 Dialog dialog
= null
;
755 AlertDialog
.Builder builder
;
757 case DIALOG_SHORT_WAIT
: {
758 ProgressDialog working_dialog
= new ProgressDialog(this);
759 working_dialog
.setMessage(getResources().getString(
760 R
.string
.wait_a_moment
));
761 working_dialog
.setIndeterminate(true
);
762 working_dialog
.setCancelable(false
);
763 dialog
= working_dialog
;
766 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
768 String
[] items
= null
;
770 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
771 getString(R
.string
.actionbar_upload_from_apps
),
772 getString(R
.string
.actionbar_failed_instant_upload
) };
774 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
775 getString(R
.string
.actionbar_upload_from_apps
) };
777 if (InstantUploadActivity
.IS_ENABLED
)
782 builder
= new AlertDialog
.Builder(this);
783 builder
.setTitle(R
.string
.actionbar_upload
);
784 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
785 public void onClick(DialogInterface dialog
, int item
) {
788 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
789 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
790 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
792 // TODO create and handle new fragment
793 // LocalFileListFragment
795 } else if (item
== 1) {
796 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
797 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
798 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
799 ACTION_SELECT_CONTENT_FROM_APPS
);
800 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
801 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
802 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
803 startActivity(action
);
807 dialog
= builder
.create();
810 case DIALOG_SSL_VALIDATOR
: {
811 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
814 case DIALOG_CERT_NOT_SAVED
: {
815 builder
= new AlertDialog
.Builder(this);
816 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
817 builder
.setCancelable(false
);
818 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
820 public void onClick(DialogInterface dialog
, int which
) {
824 dialog
= builder
.create();
836 * Show loading dialog
838 public void showLoadingDialog() {
840 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
841 FragmentManager fm
= getSupportFragmentManager();
842 FragmentTransaction ft
= fm
.beginTransaction();
843 loading
.show(ft
, DIALOG_WAIT_TAG
);
848 * Dismiss loading dialog
850 public void dismissLoadingDialog(){
851 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
853 LoadingDialog loading
= (LoadingDialog
) frag
;
860 * Translates a content URI of an image to a physical path
862 * @param uri The URI to resolve
863 * @return The path to the image or null if it could not be found
865 public String
getPath(Uri uri
) {
866 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
867 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
868 if (cursor
!= null
) {
869 int column_index
= cursor
870 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
871 cursor
.moveToFirst();
872 return cursor
.getString(column_index
);
878 * Pushes a directory to the drop down list
879 * @param directory to push
880 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
882 public void pushDirname(OCFile directory
) {
883 if(!directory
.isFolder()){
884 throw new IllegalArgumentException("Only directories may be pushed!");
886 mDirectories
.insert(directory
.getFileName(), 0);
891 * Pops a directory name from the drop down list
892 * @return True, unless the stack is empty
894 public boolean popDirname() {
895 mDirectories
.remove(mDirectories
.getItem(0));
896 return !mDirectories
.isEmpty();
899 // Custom array adapter to override text colors
900 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
902 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
906 public View
getView(int position
, View convertView
, ViewGroup parent
) {
907 View v
= super.getView(position
, convertView
, parent
);
909 ((TextView
) v
).setTextColor(getResources().getColorStateList(
910 android
.R
.color
.white
));
914 public View
getDropDownView(int position
, View convertView
,
916 View v
= super.getDropDownView(position
, convertView
, parent
);
918 ((TextView
) v
).setTextColor(getResources().getColorStateList(
919 android
.R
.color
.white
));
926 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
929 * {@link BroadcastReceiver} to enable syncing feedback in UI
932 public void onReceive(Context context
, Intent intent
) {
933 boolean inProgress
= intent
.getBooleanExtra(FileSyncService
.IN_PROGRESS
, false
);
934 String accountName
= intent
.getStringExtra(FileSyncService
.ACCOUNT_NAME
);
935 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncService
.SYNC_RESULT
);
937 if (getAccount() != null
&& accountName
.equals(getAccount().name
)
938 && mStorageManager
!= null
) {
940 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
942 OCFile currentFile
= (getFile() == null
) ? null
: mStorageManager
.getFileByPath(getFile().getRemotePath());
943 OCFile currentDir
= (getCurrentDir() == null
) ? null
: mStorageManager
.getFileByPath(getCurrentDir().getRemotePath());
945 if (currentDir
== null
) {
946 // current folder was removed from the server
947 Toast
.makeText( FileDisplayActivity
.this,
948 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
954 if (currentFile
== null
&& !getFile().isFolder()) {
955 // currently selected file was removed in the server, and now we know it
956 cleanSecondFragment();
957 currentFile
= currentDir
;
960 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
961 OCFileListFragment fileListFragment
= getListOfFilesFragment();
962 if (fileListFragment
!= null
) {
963 fileListFragment
.listDirectory(currentDir
);
966 setFile(currentFile
);
969 if (!mRefreshSharesInProgress
) {
970 /// get the shared files
971 if (isSharedSupported()) {
974 setSupportProgressBarIndeterminateVisibility(inProgress
);
976 setSupportProgressBarIndeterminateVisibility(true
);
979 removeStickyBroadcast(intent
);
980 mSyncInProgress
= inProgress
;
984 if (synchResult
!= null
) {
985 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
986 mLastSslUntrustedServerResult
= synchResult
;
987 showDialog(DIALOG_SSL_VALIDATOR
);
994 private class UploadFinishReceiver
extends BroadcastReceiver
{
996 * Once the file upload has finished -> update view
997 * @author David A. Velasco
998 * {@link BroadcastReceiver} to enable upload feedback in UI
1001 public void onReceive(Context context
, Intent intent
) {
1002 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1003 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1004 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1005 OCFile currentDir
= getCurrentDir();
1006 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1007 if (sameAccount
&& isDescendant
) {
1008 refeshListOfFilesFragment();
1016 * Class waiting for broadcast events from the {@link FielDownloader} service.
1018 * Updates the UI when a download is started or finished, provided that it is relevant for the
1021 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1023 public void onReceive(Context context
, Intent intent
) {
1024 boolean sameAccount
= isSameAccount(context
, intent
);
1025 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1026 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1028 if (sameAccount
&& isDescendant
) {
1029 refeshListOfFilesFragment();
1030 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1033 removeStickyBroadcast(intent
);
1036 private boolean isDescendant(String downloadedRemotePath
) {
1037 OCFile currentDir
= getCurrentDir();
1038 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1041 private boolean isSameAccount(Context context
, Intent intent
) {
1042 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1043 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1049 * Class waiting for broadcast events from the {@link OperationsService}.
1051 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1052 * operation performed in {@link OperationsService}.
1054 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1055 * probably all the operations associated to the app model.
1057 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1060 public void onReceive(Context context
, Intent intent
) {
1061 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1063 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1064 mRefreshSharesInProgress
= false
;
1066 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1067 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1068 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1069 && mStorageManager
!= null
1071 refeshListOfFilesFragment();
1073 if ((getSharesResult
!= null
) &&
1074 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1075 mLastSslUntrustedServerResult
= getSharesResult
;
1076 showDialog(DIALOG_SSL_VALIDATOR
);
1079 setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress
|| mSyncInProgress
);
1091 public FileDataStorageManager
getStorageManager() {
1092 return mStorageManager
;
1096 public void browseToRoot() {
1097 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1098 if (listOfFiles
!= null
) { // should never be null, indeed
1099 while (mDirectories
.getCount() > 1) {
1102 OCFile root
= mStorageManager
.getFileByPath(OCFile
.ROOT_PATH
);
1103 listOfFiles
.listDirectory(root
);
1104 setFile(listOfFiles
.getCurrentFile());
1105 startSyncFolderOperation(root
);
1107 cleanSecondFragment();
1111 public void browseTo(OCFile folder
) {
1112 if (folder
== null
|| !folder
.isFolder()) {
1113 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1115 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1116 if (listOfFiles
!= null
) {
1117 setNavigationListWithFolder(folder
);
1118 listOfFiles
.listDirectory(folder
);
1119 setFile(listOfFiles
.getCurrentFile());
1120 startSyncFolderOperation(folder
);
1122 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1124 cleanSecondFragment();
1131 * Updates action bar and second fragment, if in dual pane mode.
1134 public void onBrowsedDownTo(OCFile directory
) {
1135 pushDirname(directory
);
1136 cleanSecondFragment();
1139 startSyncFolderOperation(directory
);
1144 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1146 * @param file Image {@link OCFile} to show.
1149 public void startImagePreview(OCFile file
) {
1150 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1151 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1152 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1153 startActivity(showDetailsIntent
);
1157 * Stars the preview of an already down media {@link OCFile}.
1159 * @param file Media {@link OCFile} to preview.
1160 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1161 * @param autoplay When 'true', the playback will start without user interactions.
1164 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1165 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1166 setSecondFragment(mediaFragment
);
1167 updateFragmentsVisibility(true
);
1168 updateNavigationElementsInActionBar(file
);
1173 * Requests the download of the received {@link OCFile} , updates the UI
1174 * to monitor the download progress and prepares the activity to preview
1175 * or open the file when the download finishes.
1177 * @param file {@link OCFile} to download and preview.
1180 public void startDownloadForPreview(OCFile file
) {
1181 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1182 setSecondFragment(detailFragment
);
1183 mWaitingToPreview
= file
;
1184 requestForDownload();
1185 updateFragmentsVisibility(true
);
1186 updateNavigationElementsInActionBar(file
);
1192 * Shows the information of the {@link OCFile} received as a
1193 * parameter in the second fragment.
1195 * @param file {@link OCFile} whose details will be shown
1198 public void showDetails(OCFile file
) {
1199 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1200 setSecondFragment(detailFragment
);
1201 updateFragmentsVisibility(true
);
1202 updateNavigationElementsInActionBar(file
);
1210 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1211 ActionBar actionBar
= getSupportActionBar();
1212 if (chosenFile
== null
|| mDualPane
) {
1213 // only list of files - set for browsing through folders
1214 OCFile currentDir
= getCurrentDir();
1215 actionBar
.setDisplayHomeAsUpEnabled(currentDir
!= null
&& currentDir
.getParentId() != 0);
1216 actionBar
.setDisplayShowTitleEnabled(false
);
1217 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
1218 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1221 actionBar
.setDisplayHomeAsUpEnabled(true
);
1222 actionBar
.setDisplayShowTitleEnabled(true
);
1223 actionBar
.setTitle(chosenFile
.getFileName());
1224 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1233 public void onFileStateChanged() {
1234 refeshListOfFilesFragment();
1235 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1243 public FileDownloaderBinder
getFileDownloaderBinder() {
1244 return mDownloaderBinder
;
1252 public FileUploaderBinder
getFileUploaderBinder() {
1253 return mUploaderBinder
;
1257 /** Defines callbacks for service binding, passed to bindService() */
1258 private class ListServiceConnection
implements ServiceConnection
{
1261 public void onServiceConnected(ComponentName component
, IBinder service
) {
1262 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1263 Log_OC
.d(TAG
, "Download service connected");
1264 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1265 if (mWaitingToPreview
!= null
) {
1266 requestForDownload();
1269 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1270 Log_OC
.d(TAG
, "Upload service connected");
1271 mUploaderBinder
= (FileUploaderBinder
) service
;
1275 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1276 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1277 if (listOfFiles
!= null
) {
1278 listOfFiles
.listDirectory();
1280 FileFragment secondFragment
= getSecondFragment();
1281 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1282 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1283 detailFragment
.listenForTransferProgress();
1284 detailFragment
.updateFileDetails(false
, false
);
1289 public void onServiceDisconnected(ComponentName component
) {
1290 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1291 Log_OC
.d(TAG
, "Download service disconnected");
1292 mDownloaderBinder
= null
;
1293 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1294 Log_OC
.d(TAG
, "Upload service disconnected");
1295 mUploaderBinder
= null
;
1303 * Launch an intent to request the PIN code to the user before letting him use the app
1305 private void requestPinCode() {
1306 boolean pinStart
= false
;
1307 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1308 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1310 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1311 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1318 public void onSavedCertificate() {
1319 startSyncFolderOperation(getCurrentDir());
1324 public void onFailedSavingCertificate() {
1325 showDialog(DIALOG_CERT_NOT_SAVED
);
1330 * Updates the view associated to the activity after the finish of some operation over files
1331 * in the current account.
1333 * @param operation Removal operation performed.
1334 * @param result Result of the removal.
1337 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1338 if (operation
instanceof RemoveFileOperation
) {
1339 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1341 } else if (operation
instanceof RenameFileOperation
) {
1342 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1344 } else if (operation
instanceof SynchronizeFileOperation
) {
1345 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1347 } else if (operation
instanceof CreateFolderOperation
) {
1348 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1354 * Updates the view associated to the activity after the finish of an operation trying to remove a
1357 * @param operation Removal operation performed.
1358 * @param result Result of the removal.
1360 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1361 dismissLoadingDialog();
1362 if (result
.isSuccess()) {
1363 Toast msg
= Toast
.makeText(this, R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1365 OCFile removedFile
= operation
.getFile();
1366 getSecondFragment();
1367 FileFragment second
= getSecondFragment();
1368 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1369 cleanSecondFragment();
1371 if (mStorageManager
.getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1372 refeshListOfFilesFragment();
1376 Toast msg
= Toast
.makeText(this, R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1378 if (result
.isSslRecoverableException()) {
1379 mLastSslUntrustedServerResult
= result
;
1380 showDialog(DIALOG_SSL_VALIDATOR
);
1386 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1388 * @param operation Creation operation performed.
1389 * @param result Result of the creation.
1391 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1392 if (result
.isSuccess()) {
1393 dismissLoadingDialog();
1394 refeshListOfFilesFragment();
1397 dismissLoadingDialog();
1398 if (result
.getCode() == ResultCode
.INVALID_CHARACTER_IN_NAME
) {
1399 Toast
.makeText(FileDisplayActivity
.this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
).show();
1402 Toast msg
= Toast
.makeText(FileDisplayActivity
.this, R
.string
.create_dir_fail_msg
, Toast
.LENGTH_LONG
);
1405 } catch (NotFoundException e
) {
1406 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1414 * Updates the view associated to the activity after the finish of an operation trying to rename a
1417 * @param operation Renaming operation performed.
1418 * @param result Result of the renaming.
1420 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1421 dismissLoadingDialog();
1422 OCFile renamedFile
= operation
.getFile();
1423 if (result
.isSuccess()) {
1425 FileFragment details
= getSecondFragment();
1426 if (details
!= null
&& details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1427 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1430 if (mStorageManager
.getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1431 refeshListOfFilesFragment();
1435 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1436 Toast msg
= Toast
.makeText(this, R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1438 // TODO throw again the new rename dialog
1439 } if (result
.getCode().equals(ResultCode
.INVALID_CHARACTER_IN_NAME
)) {
1440 Toast msg
= Toast
.makeText(this, R
.string
.filename_forbidden_characters
, Toast
.LENGTH_LONG
);
1443 Toast msg
= Toast
.makeText(this, R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1445 if (result
.isSslRecoverableException()) {
1446 mLastSslUntrustedServerResult
= result
;
1447 showDialog(DIALOG_SSL_VALIDATOR
);
1454 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1455 dismissLoadingDialog();
1456 OCFile syncedFile
= operation
.getLocalFile();
1457 if (!result
.isSuccess()) {
1458 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1459 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1460 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1461 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1467 if (operation
.transferWasRequested()) {
1468 refeshListOfFilesFragment();
1469 onTransferStateChanged(syncedFile
, true
, true
);
1472 Toast msg
= Toast
.makeText(this, R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1483 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1485 FileFragment details
= getSecondFragment();
1486 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1487 if (downloading
|| uploading
) {
1488 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1490 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1497 public void onDismiss(EditNameDialog dialog
) {
1498 if (dialog
.getResult()) {
1499 String newDirectoryName
= dialog
.getNewFilename().trim();
1500 Log_OC
.d(TAG
, "'create directory' dialog dismissed with new name " + newDirectoryName
);
1501 if (newDirectoryName
.length() > 0) {
1502 String path
= getCurrentDir().getRemotePath();
1505 path
+= newDirectoryName
+ OCFile
.PATH_SEPARATOR
;
1506 RemoteOperation operation
= new CreateFolderOperation(path
, false
, mStorageManager
);
1507 operation
.execute( getAccount(),
1508 FileDisplayActivity
.this,
1509 FileDisplayActivity
.this,
1511 FileDisplayActivity
.this);
1513 showLoadingDialog();
1519 private void requestForDownload() {
1520 Account account
= getAccount();
1521 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1522 Intent i
= new Intent(this, FileDownloader
.class);
1523 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1524 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1530 private OCFile
getCurrentDir() {
1531 OCFile file
= getFile();
1533 if (file
.isFolder()) {
1535 } else if (mStorageManager
!= null
) {
1536 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1537 return mStorageManager
.getFileByPath(parentPath
);
1543 public void startSyncFolderOperation(OCFile folder
) {
1544 long currentSyncTime
= System
.currentTimeMillis();
1546 mSyncInProgress
= true
;
1548 // perform folder synchronization
1549 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1552 getStorageManager(),
1554 getApplicationContext()
1556 synchFolderOp
.execute(getAccount(), this, null
, null
, this);
1558 setSupportProgressBarIndeterminateVisibility(true
);
1562 private void startGetShares() {
1563 // Get shared files/folders
1564 Intent intent
= new Intent(this, OperationsService
.class);
1565 intent
.putExtra(OperationsService
.EXTRA_ACCOUNT
, getAccount());
1566 startService(intent
);
1568 mRefreshSharesInProgress
= true
;
1569 setSupportProgressBarIndeterminateVisibility(true
);
1574 public void shareFileWithLink(OCFile file
) {
1575 CreateShareOperation createShare
= new CreateShareOperation(file
.getRemotePath(), ShareType
.PUBLIC_LINK
, "", false
, "", 1);
1576 createShare
.execute(getStorageManager(), this, this, mHandler
, this);