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
;
78 import com
.owncloud
.android
.operations
.CreateShareOperation
;
79 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
80 import com
.owncloud
.android
.operations
.RenameFileOperation
;
81 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
82 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
83 import com
.owncloud
.android
.services
.OperationsService
;
84 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
85 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
86 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
87 import com
.owncloud
.android
.ui
.dialog
.LoadingDialog
;
88 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
89 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
90 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
91 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
92 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
93 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
94 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
95 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
96 import com
.owncloud
.android
.utils
.DisplayUtils
;
97 import com
.owncloud
.android
.utils
.Log_OC
;
101 * Displays, what files the user has available in his ownCloud.
103 * @author Bartek Przybylski
104 * @author David A. Velasco
107 public class FileDisplayActivity
extends FileActivity
implements
108 OCFileListFragment
.ContainerActivity
, FileDetailFragment
.ContainerActivity
, OnNavigationListener
, OnSslValidatorListener
, OnRemoteOperationListener
, EditNameDialogListener
{
110 private ArrayAdapter
<String
> mDirectories
;
112 /** Access point to the cached database for the current ownCloud {@link Account} */
113 private FileDataStorageManager mStorageManager
= null
;
115 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
116 private UploadFinishReceiver mUploadFinishReceiver
;
117 private DownloadFinishReceiver mDownloadFinishReceiver
;
118 private OperationsServiceReceiver mOperationsServiceReceiver
;
119 private FileDownloaderBinder mDownloaderBinder
= null
;
120 private FileUploaderBinder mUploaderBinder
= null
;
121 private ServiceConnection mDownloadConnection
= null
, mUploadConnection
= null
;
122 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
124 private boolean mDualPane
;
125 private View mLeftFragmentContainer
;
126 private View mRightFragmentContainer
;
128 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
129 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
130 private static final String KEY_REFRESH_SHARES_IN_PROGRESS
= "SHARES_IN_PROGRESS";
132 public static final int DIALOG_SHORT_WAIT
= 0;
133 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
134 private static final int DIALOG_SSL_VALIDATOR
= 2;
135 private static final int DIALOG_CERT_NOT_SAVED
= 3;
137 private static final String DIALOG_WAIT_TAG
= "DIALOG_WAIT";
139 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
141 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
142 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
144 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
146 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
147 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
149 private OCFile mWaitingToPreview
;
150 private Handler mHandler
;
152 private boolean mSyncInProgress
= false
;
153 private boolean mRefreshSharesInProgress
= false
;
156 protected void onCreate(Bundle savedInstanceState
) {
157 Log_OC
.d(TAG
, "onCreate() start");
158 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
160 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
162 mHandler
= new Handler();
164 /// bindings to transference services
165 mUploadConnection
= new ListServiceConnection();
166 mDownloadConnection
= new ListServiceConnection();
167 bindService(new Intent(this, FileUploader
.class), mUploadConnection
, Context
.BIND_AUTO_CREATE
);
168 bindService(new Intent(this, FileDownloader
.class), mDownloadConnection
, Context
.BIND_AUTO_CREATE
);
170 // PIN CODE request ; best location is to decide, let's try this first
171 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
173 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
178 Intent observer_intent
= new Intent(this, FileObserverService
.class);
179 observer_intent
.putExtra(FileObserverService
.KEY_FILE_CMD
, FileObserverService
.CMD_INIT_OBSERVED_LIST
);
180 startService(observer_intent
);
182 /// Load of saved instance state
183 if(savedInstanceState
!= null
) {
184 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
185 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
186 mRefreshSharesInProgress
= savedInstanceState
.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS
);
189 mWaitingToPreview
= null
;
190 mSyncInProgress
= false
;
191 mRefreshSharesInProgress
= false
;
196 // Inflate and set the layout view
197 setContentView(R
.layout
.files
);
198 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
199 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
200 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
201 if (savedInstanceState
== null
) {
202 createMinFragments();
206 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
207 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
208 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
); // always AFTER setContentView(...) ; to work around bug in its implementation
210 Log_OC
.d(TAG
, "onCreate() end");
214 protected void onStart() {
216 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
220 protected void onDestroy() {
222 if (mDownloadConnection
!= null
)
223 unbindService(mDownloadConnection
);
224 if (mUploadConnection
!= null
)
225 unbindService(mUploadConnection
);
230 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
233 protected void onAccountSet(boolean stateWasRecovered
) {
234 if (getAccount() != null
) {
235 mStorageManager
= new FileDataStorageManager(getAccount(), getContentResolver());
237 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
238 OCFile file
= getFile();
239 // get parent from path
240 String parentPath
= "";
242 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
243 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
244 // get parent from path
245 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
246 if (mStorageManager
.getFileByPath(parentPath
) == null
)
247 file
= null
; // not able to know the directory where the file is uploading
249 file
= mStorageManager
.getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
253 // fall back to root folder
254 file
= mStorageManager
.getFileByPath(OCFile
.ROOT_PATH
); // never returns null
257 setNavigationListWithFolder(file
);
259 if (!stateWasRecovered
) {
260 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
261 initFragmentsWithFile();
262 if (file
.isFolder()) {
263 startSyncFolderOperation(file
);
267 updateFragmentsVisibility(!file
.isFolder());
268 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
273 Log_OC
.wtf(TAG
, "onAccountChanged was called with NULL account associated!");
278 private void setNavigationListWithFolder(OCFile file
) {
279 mDirectories
.clear();
280 OCFile fileIt
= file
;
282 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
283 if (fileIt
.isFolder()) {
284 mDirectories
.add(fileIt
.getFileName());
286 //fileIt = mStorageManager.getFileById(fileIt.getParentId());
287 // get parent from path
288 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
289 fileIt
= mStorageManager
.getFileByPath(parentPath
);
291 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
295 private void createMinFragments() {
296 OCFileListFragment listOfFiles
= new OCFileListFragment();
297 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
298 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
299 transaction
.commit();
302 private void initFragmentsWithFile() {
303 if (getAccount() != null
&& getFile() != null
) {
305 OCFileListFragment listOfFiles
= getListOfFilesFragment();
306 if (listOfFiles
!= null
) {
307 listOfFiles
.listDirectory(getCurrentDir());
309 Log
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
313 OCFile file
= getFile();
314 Fragment secondFragment
= chooseInitialSecondFragment(file
);
315 if (secondFragment
!= null
) {
316 setSecondFragment(secondFragment
);
317 updateFragmentsVisibility(true
);
318 updateNavigationElementsInActionBar(file
);
321 cleanSecondFragment();
325 Log
.wtf(TAG
, "initFragments() called with invalid NULLs!");
326 if (getAccount() == null
) {
327 Log
.wtf(TAG
, "\t account is NULL");
329 if (getFile() == null
) {
330 Log
.wtf(TAG
, "\t file is NULL");
335 private Fragment
chooseInitialSecondFragment(OCFile file
) {
336 Fragment secondFragment
= null
;
337 if (file
!= null
&& !file
.isFolder()) {
338 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
339 && file
.getLastSyncDateForProperties() > 0 // temporal fix
341 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
342 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
343 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
346 secondFragment
= new FileDetailFragment(file
, getAccount());
349 return secondFragment
;
354 * Replaces the second fragment managed by the activity with the received as
357 * Assumes never will be more than two fragments managed at the same time.
359 * @param fragment New second Fragment to set.
361 private void setSecondFragment(Fragment fragment
) {
362 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
363 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
364 transaction
.commit();
368 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
370 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
377 } else if (existsSecondFragment
) {
378 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
379 mLeftFragmentContainer
.setVisibility(View
.GONE
);
381 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
382 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
386 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
387 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
389 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
390 mRightFragmentContainer
.setVisibility(View
.GONE
);
396 private OCFileListFragment
getListOfFilesFragment() {
397 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
398 if (listOfFiles
!= null
) {
399 return (OCFileListFragment
)listOfFiles
;
401 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
405 protected FileFragment
getSecondFragment() {
406 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
407 if (second
!= null
) {
408 return (FileFragment
)second
;
413 public void cleanSecondFragment() {
414 Fragment second
= getSecondFragment();
415 if (second
!= null
) {
416 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
420 updateFragmentsVisibility(false
);
421 updateNavigationElementsInActionBar(null
);
424 protected void refeshListOfFilesFragment() {
425 OCFileListFragment fileListFragment
= getListOfFilesFragment();
426 if (fileListFragment
!= null
) {
427 fileListFragment
.listDirectory();
431 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
432 FileFragment secondFragment
= getSecondFragment();
433 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
434 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
435 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
436 OCFile fileInFragment
= detailsFragment
.getFile();
437 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
438 // the user browsed to other file ; forget the automatic preview
439 mWaitingToPreview
= null
;
441 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
442 // grant that the right panel updates the progress bar
443 detailsFragment
.listenForTransferProgress();
444 detailsFragment
.updateFileDetails(true
, false
);
446 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
447 // update the right panel
448 boolean detailsFragmentChanged
= false
;
451 mWaitingToPreview
= mStorageManager
.getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
452 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
453 startMediaPreview(mWaitingToPreview
, 0, true
);
454 detailsFragmentChanged
= true
;
456 openFile(mWaitingToPreview
);
459 mWaitingToPreview
= null
;
461 if (!detailsFragmentChanged
) {
462 detailsFragment
.updateFileDetails(false
, (success
));
470 public boolean onCreateOptionsMenu(Menu menu
) {
471 MenuInflater inflater
= getSherlock().getMenuInflater();
472 inflater
.inflate(R
.menu
.main_menu
, menu
);
477 public boolean onOptionsItemSelected(MenuItem item
) {
478 boolean retval
= true
;
479 switch (item
.getItemId()) {
480 case R
.id
.action_create_dir
: {
481 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.uploader_info_dirname
), "", -1, -1, this);
482 dialog
.show(getSupportFragmentManager(), "createdirdialog");
485 case R
.id
.action_sync_account
: {
486 startSynchronization();
489 case R
.id
.action_upload
: {
490 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
493 case R
.id
.action_settings
: {
494 Intent settingsIntent
= new Intent(this, Preferences
.class);
495 startActivity(settingsIntent
);
498 case android
.R
.id
.home
: {
499 FileFragment second
= getSecondFragment();
500 OCFile currentDir
= getCurrentDir();
501 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
502 (second
!= null
&& second
.getFile() != null
)) {
509 retval
= super.onOptionsItemSelected(item
);
514 private void startSynchronization() {
515 Log_OC
.e(TAG
, "Got to start sync");
516 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
517 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
518 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
519 Bundle bundle
= new Bundle();
520 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
521 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
522 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
523 ContentResolver
.requestSync(
525 MainApp
.getAuthority(), bundle
);
527 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
528 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
529 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
530 builder
.setExpedited(true
);
531 builder
.setManual(true
);
533 SyncRequest request
= builder
.build();
534 ContentResolver
.requestSync(request
);
540 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
541 if (itemPosition
!= 0) {
542 String targetPath
= "";
543 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
544 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
546 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
547 OCFile targetFolder
= mStorageManager
.getFileByPath(targetPath
);
548 if (targetFolder
!= null
) {
549 browseTo(targetFolder
);
552 // the next operation triggers a new call to this method, but it's necessary to
553 // ensure that the name exposed in the action bar is the current directory when the
554 // user selected it in the navigation list
555 getSupportActionBar().setSelectedNavigationItem(0);
561 * Called, when the user selected something for uploading
563 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
564 super.onActivityResult(requestCode
, resultCode
, data
);
566 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
567 requestSimpleUpload(data
, resultCode
);
569 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
570 requestMultipleUpload(data
, resultCode
);
575 private void requestMultipleUpload(Intent data
, int resultCode
) {
576 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
577 if (filePaths
!= null
) {
578 String
[] remotePaths
= new String
[filePaths
.length
];
579 String remotePathBase
= "";
580 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
581 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
583 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
584 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
585 for (int j
= 0; j
< remotePaths
.length
; j
++) {
586 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
589 Intent i
= new Intent(this, FileUploader
.class);
590 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
591 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
592 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
593 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
594 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
595 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
599 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
600 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
607 private void requestSimpleUpload(Intent data
, int resultCode
) {
608 String filepath
= null
;
610 Uri selectedImageUri
= data
.getData();
612 String filemanagerstring
= selectedImageUri
.getPath();
613 String selectedImagePath
= getPath(selectedImageUri
);
615 if (selectedImagePath
!= null
)
616 filepath
= selectedImagePath
;
618 filepath
= filemanagerstring
;
620 } catch (Exception e
) {
621 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
625 if (filepath
== null
) {
626 Log_OC
.e(TAG
, "Couldnt resolve path to file");
627 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
633 Intent i
= new Intent(this, FileUploader
.class);
634 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
636 String remotepath
= new String();
637 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
638 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
640 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
641 remotepath
+= OCFile
.PATH_SEPARATOR
;
642 remotepath
+= new File(filepath
).getName();
644 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
645 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
646 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
647 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
648 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
653 public void onBackPressed() {
654 OCFileListFragment listOfFiles
= getListOfFilesFragment();
655 if (mDualPane
|| getSecondFragment() == null
) {
656 if (listOfFiles
!= null
) { // should never be null, indeed
657 if (mDirectories
.getCount() <= 1) {
661 int levelsUp
= listOfFiles
.onBrowseUp();
662 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
667 if (listOfFiles
!= null
) { // should never be null, indeed
668 setFile(listOfFiles
.getCurrentFile());
670 cleanSecondFragment();
675 protected void onSaveInstanceState(Bundle outState
) {
676 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
677 Log_OC
.e(TAG
, "onSaveInstanceState() start");
678 super.onSaveInstanceState(outState
);
679 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
680 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
681 outState
.putBoolean(FileDisplayActivity
.KEY_REFRESH_SHARES_IN_PROGRESS
, mRefreshSharesInProgress
);
683 Log_OC
.d(TAG
, "onSaveInstanceState() end");
689 protected void onResume() {
691 Log_OC
.e(TAG
, "onResume() start");
693 // Listen for sync messages
694 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncService
.getSyncMessage());
695 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
696 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
698 // Listen for upload messages
699 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
700 mUploadFinishReceiver
= new UploadFinishReceiver();
701 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
703 // Listen for download messages
704 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
705 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
706 mDownloadFinishReceiver
= new DownloadFinishReceiver();
707 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
709 // Listen for messages from the OperationsService
710 IntentFilter operationsIntentFilter
= new IntentFilter(OperationsService
.ACTION_OPERATION_ADDED
);
711 operationsIntentFilter
.addAction(OperationsService
.ACTION_OPERATION_FINISHED
);
712 mOperationsServiceReceiver
= new OperationsServiceReceiver();
713 LocalBroadcastManager
.getInstance(this).registerReceiver(mOperationsServiceReceiver
, operationsIntentFilter
);
715 Log_OC
.d(TAG
, "onResume() end");
720 protected void onPause() {
722 Log_OC
.e(TAG
, "onPause() start");
723 if (mSyncBroadcastReceiver
!= null
) {
724 unregisterReceiver(mSyncBroadcastReceiver
);
725 mSyncBroadcastReceiver
= null
;
727 if (mUploadFinishReceiver
!= null
) {
728 unregisterReceiver(mUploadFinishReceiver
);
729 mUploadFinishReceiver
= null
;
731 if (mDownloadFinishReceiver
!= null
) {
732 unregisterReceiver(mDownloadFinishReceiver
);
733 mDownloadFinishReceiver
= null
;
735 if (mOperationsServiceReceiver
!= null
) {
736 LocalBroadcastManager
.getInstance(this).unregisterReceiver(mOperationsServiceReceiver
);
737 mOperationsServiceReceiver
= null
;
739 Log_OC
.d(TAG
, "onPause() end");
744 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
745 if (id
== DIALOG_SSL_VALIDATOR
&& mLastSslUntrustedServerResult
!= null
) {
746 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
752 protected Dialog
onCreateDialog(int id
) {
753 Dialog dialog
= null
;
754 AlertDialog
.Builder builder
;
756 case DIALOG_SHORT_WAIT
: {
757 ProgressDialog working_dialog
= new ProgressDialog(this);
758 working_dialog
.setMessage(getResources().getString(
759 R
.string
.wait_a_moment
));
760 working_dialog
.setIndeterminate(true
);
761 working_dialog
.setCancelable(false
);
762 dialog
= working_dialog
;
765 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
767 String
[] items
= null
;
769 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
770 getString(R
.string
.actionbar_upload_from_apps
),
771 getString(R
.string
.actionbar_failed_instant_upload
) };
773 String
[] commonItems
= { getString(R
.string
.actionbar_upload_files
),
774 getString(R
.string
.actionbar_upload_from_apps
) };
776 if (InstantUploadActivity
.IS_ENABLED
)
781 builder
= new AlertDialog
.Builder(this);
782 builder
.setTitle(R
.string
.actionbar_upload
);
783 builder
.setItems(items
, new DialogInterface
.OnClickListener() {
784 public void onClick(DialogInterface dialog
, int item
) {
787 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
788 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
789 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
791 // TODO create and handle new fragment
792 // LocalFileListFragment
794 } else if (item
== 1) {
795 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
796 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
797 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
798 ACTION_SELECT_CONTENT_FROM_APPS
);
799 } else if (item
== 2 && InstantUploadActivity
.IS_ENABLED
) {
800 Intent action
= new Intent(FileDisplayActivity
.this, InstantUploadActivity
.class);
801 action
.putExtra(FileUploader
.KEY_ACCOUNT
, FileDisplayActivity
.this.getAccount());
802 startActivity(action
);
806 dialog
= builder
.create();
809 case DIALOG_SSL_VALIDATOR
: {
810 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
813 case DIALOG_CERT_NOT_SAVED
: {
814 builder
= new AlertDialog
.Builder(this);
815 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
816 builder
.setCancelable(false
);
817 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
819 public void onClick(DialogInterface dialog
, int which
) {
823 dialog
= builder
.create();
835 * Show loading dialog
837 public void showLoadingDialog() {
839 LoadingDialog loading
= new LoadingDialog(getResources().getString(R
.string
.wait_a_moment
));
840 FragmentManager fm
= getSupportFragmentManager();
841 FragmentTransaction ft
= fm
.beginTransaction();
842 loading
.show(ft
, DIALOG_WAIT_TAG
);
847 * Dismiss loading dialog
849 public void dismissLoadingDialog(){
850 Fragment frag
= getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG
);
852 LoadingDialog loading
= (LoadingDialog
) frag
;
859 * Translates a content URI of an image to a physical path
861 * @param uri The URI to resolve
862 * @return The path to the image or null if it could not be found
864 public String
getPath(Uri uri
) {
865 String
[] projection
= { MediaStore
.Images
.Media
.DATA
};
866 Cursor cursor
= managedQuery(uri
, projection
, null
, null
, null
);
867 if (cursor
!= null
) {
868 int column_index
= cursor
869 .getColumnIndexOrThrow(MediaStore
.Images
.Media
.DATA
);
870 cursor
.moveToFirst();
871 return cursor
.getString(column_index
);
877 * Pushes a directory to the drop down list
878 * @param directory to push
879 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
881 public void pushDirname(OCFile directory
) {
882 if(!directory
.isFolder()){
883 throw new IllegalArgumentException("Only directories may be pushed!");
885 mDirectories
.insert(directory
.getFileName(), 0);
890 * Pops a directory name from the drop down list
891 * @return True, unless the stack is empty
893 public boolean popDirname() {
894 mDirectories
.remove(mDirectories
.getItem(0));
895 return !mDirectories
.isEmpty();
898 // Custom array adapter to override text colors
899 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
901 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
905 public View
getView(int position
, View convertView
, ViewGroup parent
) {
906 View v
= super.getView(position
, convertView
, parent
);
908 ((TextView
) v
).setTextColor(getResources().getColorStateList(
909 android
.R
.color
.white
));
913 public View
getDropDownView(int position
, View convertView
,
915 View v
= super.getDropDownView(position
, convertView
, parent
);
917 ((TextView
) v
).setTextColor(getResources().getColorStateList(
918 android
.R
.color
.white
));
925 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
928 * {@link BroadcastReceiver} to enable syncing feedback in UI
931 public void onReceive(Context context
, Intent intent
) {
932 boolean inProgress
= intent
.getBooleanExtra(FileSyncService
.IN_PROGRESS
, false
);
933 String accountName
= intent
.getStringExtra(FileSyncService
.ACCOUNT_NAME
);
934 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncService
.SYNC_RESULT
);
936 if (getAccount() != null
&& accountName
.equals(getAccount().name
)
937 && mStorageManager
!= null
) {
939 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
);
941 OCFile currentFile
= (getFile() == null
) ? null
: mStorageManager
.getFileByPath(getFile().getRemotePath());
942 OCFile currentDir
= (getCurrentDir() == null
) ? null
: mStorageManager
.getFileByPath(getCurrentDir().getRemotePath());
944 if (currentDir
== null
) {
945 // current folder was removed from the server
946 Toast
.makeText( FileDisplayActivity
.this,
947 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
953 if (currentFile
== null
&& !getFile().isFolder()) {
954 // currently selected file was removed in the server, and now we know it
955 cleanSecondFragment();
956 currentFile
= currentDir
;
959 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
960 OCFileListFragment fileListFragment
= getListOfFilesFragment();
961 if (fileListFragment
!= null
) {
962 fileListFragment
.listDirectory(currentDir
);
965 setFile(currentFile
);
968 if (!mRefreshSharesInProgress
) {
969 /// get the shared files
970 if (isSharedSupported()) {
973 setSupportProgressBarIndeterminateVisibility(inProgress
);
975 setSupportProgressBarIndeterminateVisibility(true
);
978 removeStickyBroadcast(intent
);
979 mSyncInProgress
= inProgress
;
983 if (synchResult
!= null
) {
984 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
985 mLastSslUntrustedServerResult
= synchResult
;
986 showDialog(DIALOG_SSL_VALIDATOR
);
993 private class UploadFinishReceiver
extends BroadcastReceiver
{
995 * Once the file upload has finished -> update view
996 * @author David A. Velasco
997 * {@link BroadcastReceiver} to enable upload feedback in UI
1000 public void onReceive(Context context
, Intent intent
) {
1001 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1002 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1003 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1004 OCFile currentDir
= getCurrentDir();
1005 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) && (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1006 if (sameAccount
&& isDescendant
) {
1007 refeshListOfFilesFragment();
1015 * Class waiting for broadcast events from the {@link FielDownloader} service.
1017 * Updates the UI when a download is started or finished, provided that it is relevant for the
1020 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1022 public void onReceive(Context context
, Intent intent
) {
1023 boolean sameAccount
= isSameAccount(context
, intent
);
1024 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1025 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1027 if (sameAccount
&& isDescendant
) {
1028 refeshListOfFilesFragment();
1029 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1032 removeStickyBroadcast(intent
);
1035 private boolean isDescendant(String downloadedRemotePath
) {
1036 OCFile currentDir
= getCurrentDir();
1037 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1040 private boolean isSameAccount(Context context
, Intent intent
) {
1041 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1042 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1048 * Class waiting for broadcast events from the {@link OperationsService}.
1050 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1051 * operation performed in {@link OperationsService}.
1053 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1054 * probably all the operations associated to the app model.
1056 private class OperationsServiceReceiver
extends BroadcastReceiver
{
1059 public void onReceive(Context context
, Intent intent
) {
1060 if (OperationsService
.ACTION_OPERATION_ADDED
.equals(intent
.getAction())) {
1062 } else if (OperationsService
.ACTION_OPERATION_FINISHED
.equals(intent
.getAction())) {
1063 mRefreshSharesInProgress
= false
;
1065 Account account
= intent
.getParcelableExtra(OperationsService
.EXTRA_ACCOUNT
);
1066 RemoteOperationResult getSharesResult
= (RemoteOperationResult
)intent
.getSerializableExtra(OperationsService
.EXTRA_RESULT
);
1067 if (getAccount() != null
&& account
.name
.equals(getAccount().name
)
1068 && mStorageManager
!= null
1070 refeshListOfFilesFragment();
1072 if ((getSharesResult
!= null
) &&
1073 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
.equals(getSharesResult
.getCode())) {
1074 mLastSslUntrustedServerResult
= getSharesResult
;
1075 showDialog(DIALOG_SSL_VALIDATOR
);
1078 setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress
|| mSyncInProgress
);
1090 public FileDataStorageManager
getStorageManager() {
1091 return mStorageManager
;
1095 public void browseToRoot() {
1096 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1097 if (listOfFiles
!= null
) { // should never be null, indeed
1098 while (mDirectories
.getCount() > 1) {
1101 OCFile root
= mStorageManager
.getFileByPath(OCFile
.ROOT_PATH
);
1102 listOfFiles
.listDirectory(root
);
1103 setFile(listOfFiles
.getCurrentFile());
1104 startSyncFolderOperation(root
);
1106 cleanSecondFragment();
1110 public void browseTo(OCFile folder
) {
1111 if (folder
== null
|| !folder
.isFolder()) {
1112 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1114 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1115 if (listOfFiles
!= null
) {
1116 setNavigationListWithFolder(folder
);
1117 listOfFiles
.listDirectory(folder
);
1118 setFile(listOfFiles
.getCurrentFile());
1119 startSyncFolderOperation(folder
);
1121 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1123 cleanSecondFragment();
1130 * Updates action bar and second fragment, if in dual pane mode.
1133 public void onBrowsedDownTo(OCFile directory
) {
1134 pushDirname(directory
);
1135 cleanSecondFragment();
1138 startSyncFolderOperation(directory
);
1143 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1145 * @param file Image {@link OCFile} to show.
1148 public void startImagePreview(OCFile file
) {
1149 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1150 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1151 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1152 startActivity(showDetailsIntent
);
1156 * Stars the preview of an already down media {@link OCFile}.
1158 * @param file Media {@link OCFile} to preview.
1159 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1160 * @param autoplay When 'true', the playback will start without user interactions.
1163 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1164 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1165 setSecondFragment(mediaFragment
);
1166 updateFragmentsVisibility(true
);
1167 updateNavigationElementsInActionBar(file
);
1172 * Requests the download of the received {@link OCFile} , updates the UI
1173 * to monitor the download progress and prepares the activity to preview
1174 * or open the file when the download finishes.
1176 * @param file {@link OCFile} to download and preview.
1179 public void startDownloadForPreview(OCFile file
) {
1180 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1181 setSecondFragment(detailFragment
);
1182 mWaitingToPreview
= file
;
1183 requestForDownload();
1184 updateFragmentsVisibility(true
);
1185 updateNavigationElementsInActionBar(file
);
1191 * Shows the information of the {@link OCFile} received as a
1192 * parameter in the second fragment.
1194 * @param file {@link OCFile} whose details will be shown
1197 public void showDetails(OCFile file
) {
1198 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1199 setSecondFragment(detailFragment
);
1200 updateFragmentsVisibility(true
);
1201 updateNavigationElementsInActionBar(file
);
1209 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1210 ActionBar actionBar
= getSupportActionBar();
1211 if (chosenFile
== null
|| mDualPane
) {
1212 // only list of files - set for browsing through folders
1213 OCFile currentDir
= getCurrentDir();
1214 actionBar
.setDisplayHomeAsUpEnabled(currentDir
!= null
&& currentDir
.getParentId() != 0);
1215 actionBar
.setDisplayShowTitleEnabled(false
);
1216 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_LIST
);
1217 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1220 actionBar
.setDisplayHomeAsUpEnabled(true
);
1221 actionBar
.setDisplayShowTitleEnabled(true
);
1222 actionBar
.setTitle(chosenFile
.getFileName());
1223 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1232 public void onFileStateChanged() {
1233 refeshListOfFilesFragment();
1234 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1242 public FileDownloaderBinder
getFileDownloaderBinder() {
1243 return mDownloaderBinder
;
1251 public FileUploaderBinder
getFileUploaderBinder() {
1252 return mUploaderBinder
;
1256 /** Defines callbacks for service binding, passed to bindService() */
1257 private class ListServiceConnection
implements ServiceConnection
{
1260 public void onServiceConnected(ComponentName component
, IBinder service
) {
1261 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1262 Log_OC
.d(TAG
, "Download service connected");
1263 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1264 if (mWaitingToPreview
!= null
) {
1265 requestForDownload();
1268 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1269 Log_OC
.d(TAG
, "Upload service connected");
1270 mUploaderBinder
= (FileUploaderBinder
) service
;
1274 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1275 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1276 if (listOfFiles
!= null
) {
1277 listOfFiles
.listDirectory();
1279 FileFragment secondFragment
= getSecondFragment();
1280 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1281 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1282 detailFragment
.listenForTransferProgress();
1283 detailFragment
.updateFileDetails(false
, false
);
1288 public void onServiceDisconnected(ComponentName component
) {
1289 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1290 Log_OC
.d(TAG
, "Download service disconnected");
1291 mDownloaderBinder
= null
;
1292 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1293 Log_OC
.d(TAG
, "Upload service disconnected");
1294 mUploaderBinder
= null
;
1302 * Launch an intent to request the PIN code to the user before letting him use the app
1304 private void requestPinCode() {
1305 boolean pinStart
= false
;
1306 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1307 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1309 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1310 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1317 public void onSavedCertificate() {
1318 startSyncFolderOperation(getCurrentDir());
1323 public void onFailedSavingCertificate() {
1324 showDialog(DIALOG_CERT_NOT_SAVED
);
1329 * Updates the view associated to the activity after the finish of some operation over files
1330 * in the current account.
1332 * @param operation Removal operation performed.
1333 * @param result Result of the removal.
1336 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1337 if (operation
instanceof RemoveFileOperation
) {
1338 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1340 } else if (operation
instanceof RenameFileOperation
) {
1341 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1343 } else if (operation
instanceof SynchronizeFileOperation
) {
1344 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1346 } else if (operation
instanceof CreateFolderOperation
) {
1347 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
) {
1576 if (isSharedSupported()) {
1578 CreateShareOperation createShare
= new CreateShareOperation(file
.getRemotePath(), ShareType
.PUBLIC_LINK
, "", false
, "", 1);
1579 createShare
.execute(getStorageManager(), this, this, mHandler
, this);
1582 // Get the link --> when the operation is finished
1586 Toast t
= Toast
.makeText(this, getString(R
.string
.share_link_no_support_share_api
), Toast
.LENGTH_LONG
);