OC-2750: Fix Bug. Loading shouldn't disappear until the shared files are shown
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
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.
8 *
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.
13 *
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/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.io.File;
22
23 import android.accounts.Account;
24 import android.accounts.AccountManager;
25 import android.app.AlertDialog;
26 import android.app.Dialog;
27 import android.app.ProgressDialog;
28 import android.content.BroadcastReceiver;
29 import android.content.ComponentName;
30 import android.content.ContentResolver;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.ServiceConnection;
36 import android.content.SharedPreferences;
37 import android.content.SyncRequest;
38 import android.content.res.Resources.NotFoundException;
39 import android.database.Cursor;
40 import android.net.Uri;
41 import android.os.Bundle;
42 import android.os.Handler;
43 import android.os.IBinder;
44 import android.preference.PreferenceManager;
45 import android.provider.MediaStore;
46 import android.support.v4.app.Fragment;
47 import android.support.v4.app.FragmentManager;
48 import android.support.v4.app.FragmentTransaction;
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;
55
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;
72
73 import com.owncloud.android.operations.GetSharedFilesOperation;
74
75 import com.owncloud.android.lib.accounts.OwnCloudAccount;
76 import com.owncloud.android.lib.operations.common.OnRemoteOperationListener;
77 import com.owncloud.android.lib.operations.common.RemoteOperation;
78 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
79 import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode;
80
81 import com.owncloud.android.operations.RemoveFileOperation;
82 import com.owncloud.android.operations.RenameFileOperation;
83 import com.owncloud.android.operations.SynchronizeFileOperation;
84 import com.owncloud.android.operations.SynchronizeFolderOperation;
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;
99
100
101 /**
102 * Displays, what files the user has available in his ownCloud.
103 *
104 * @author Bartek Przybylski
105 * @author David A. Velasco
106 */
107
108 public class FileDisplayActivity extends FileActivity implements
109 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener, EditNameDialogListener {
110
111 private ArrayAdapter<String> mDirectories;
112
113 /** Access point to the cached database for the current ownCloud {@link Account} */
114 private FileDataStorageManager mStorageManager = null;
115
116 private SyncBroadcastReceiver mSyncBroadcastReceiver;
117 private UploadFinishReceiver mUploadFinishReceiver;
118 private DownloadFinishReceiver mDownloadFinishReceiver;
119 private FileDownloaderBinder mDownloaderBinder = null;
120 private FileUploaderBinder mUploaderBinder = null;
121 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
122 private RemoteOperationResult mLastSslUntrustedServerResult = null;
123
124 private boolean mDualPane;
125 private View mLeftFragmentContainer;
126 private View mRightFragmentContainer;
127
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";
131
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;
136
137 private static final String DIALOG_WAIT_TAG = "DIALOG_WAIT";
138
139 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
140
141 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
142 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
143
144 private static final String TAG = FileDisplayActivity.class.getSimpleName();
145
146 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
147 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
148
149 private OCFile mWaitingToPreview;
150 private Handler mHandler;
151
152 private boolean mSyncInProgress = false;
153 private boolean mRefreshSharesInProgress = false;
154
155 @Override
156 protected void onCreate(Bundle savedInstanceState) {
157 Log_OC.d(TAG, "onCreate() start");
158 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
159
160 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
161
162 mHandler = new Handler();
163
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);
169
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) {
172 requestPinCode();
173 } else if (getIntent().getAction() == null && savedInstanceState == null) {
174 requestPinCode();
175 }
176
177 /// file observer
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);
181
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);
187
188 } else {
189 mWaitingToPreview = null;
190 mSyncInProgress = false;
191 mRefreshSharesInProgress = false;
192 }
193
194 /// USER INTERFACE
195
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();
203 }
204
205 // Action bar setup
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
209
210 Log_OC.d(TAG, "onCreate() end");
211 }
212
213 @Override
214 protected void onStart() {
215 super.onStart();
216 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
217 }
218
219 @Override
220 protected void onDestroy() {
221 super.onDestroy();
222 if (mDownloadConnection != null)
223 unbindService(mDownloadConnection);
224 if (mUploadConnection != null)
225 unbindService(mUploadConnection);
226 }
227
228
229 /**
230 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
231 */
232 @Override
233 protected void onAccountSet(boolean stateWasRecovered) {
234 if (getAccount() != null) {
235 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
236
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 = "";
241 if (file != null) {
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
248 } else {
249 file = mStorageManager.getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
250 }
251 }
252 if (file == null) {
253 // fall back to root folder
254 file = mStorageManager.getFileByPath(OCFile.ROOT_PATH); // never returns null
255 }
256 setFile(file);
257 setNavigationListWithFolder(file);
258
259 if (!stateWasRecovered) {
260 Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
261 initFragmentsWithFile();
262 if (file.isFolder()) {
263 startSyncFolderOperation(file);
264 }
265
266 } else {
267 updateFragmentsVisibility(!file.isFolder());
268 updateNavigationElementsInActionBar(file.isFolder() ? null : file);
269 }
270
271
272 } else {
273 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
274 }
275 }
276
277
278 private void setNavigationListWithFolder(OCFile file) {
279 mDirectories.clear();
280 OCFile fileIt = file;
281 String parentPath;
282 while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
283 if (fileIt.isFolder()) {
284 mDirectories.add(fileIt.getFileName());
285 }
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);
290 }
291 mDirectories.add(OCFile.PATH_SEPARATOR);
292 }
293
294
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();
300 }
301
302 private void initFragmentsWithFile() {
303 if (getAccount() != null && getFile() != null) {
304 /// First fragment
305 OCFileListFragment listOfFiles = getListOfFilesFragment();
306 if (listOfFiles != null) {
307 listOfFiles.listDirectory(getCurrentDir());
308 } else {
309 Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
310 }
311
312 /// Second fragment
313 OCFile file = getFile();
314 Fragment secondFragment = chooseInitialSecondFragment(file);
315 if (secondFragment != null) {
316 setSecondFragment(secondFragment);
317 updateFragmentsVisibility(true);
318 updateNavigationElementsInActionBar(file);
319
320 } else {
321 cleanSecondFragment();
322 }
323
324 } else {
325 Log.wtf(TAG, "initFragments() called with invalid NULLs!");
326 if (getAccount() == null) {
327 Log.wtf(TAG, "\t account is NULL");
328 }
329 if (getFile() == null) {
330 Log.wtf(TAG, "\t file is NULL");
331 }
332 }
333 }
334
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
340 ) {
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);
344
345 } else {
346 secondFragment = new FileDetailFragment(file, getAccount());
347 }
348 }
349 return secondFragment;
350 }
351
352
353 /**
354 * Replaces the second fragment managed by the activity with the received as
355 * a parameter.
356 *
357 * Assumes never will be more than two fragments managed at the same time.
358 *
359 * @param fragment New second Fragment to set.
360 */
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();
365 }
366
367
368 private void updateFragmentsVisibility(boolean existsSecondFragment) {
369 if (mDualPane) {
370 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
371 mLeftFragmentContainer.setVisibility(View.VISIBLE);
372 }
373 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
374 mRightFragmentContainer.setVisibility(View.VISIBLE);
375 }
376
377 } else if (existsSecondFragment) {
378 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
379 mLeftFragmentContainer.setVisibility(View.GONE);
380 }
381 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
382 mRightFragmentContainer.setVisibility(View.VISIBLE);
383 }
384
385 } else {
386 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
387 mLeftFragmentContainer.setVisibility(View.VISIBLE);
388 }
389 if (mRightFragmentContainer.getVisibility() != View.GONE) {
390 mRightFragmentContainer.setVisibility(View.GONE);
391 }
392 }
393 }
394
395
396 private OCFileListFragment getListOfFilesFragment() {
397 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
398 if (listOfFiles != null) {
399 return (OCFileListFragment)listOfFiles;
400 }
401 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
402 return null;
403 }
404
405 protected FileFragment getSecondFragment() {
406 Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
407 if (second != null) {
408 return (FileFragment)second;
409 }
410 return null;
411 }
412
413 public void cleanSecondFragment() {
414 Fragment second = getSecondFragment();
415 if (second != null) {
416 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
417 tr.remove(second);
418 tr.commit();
419 }
420 updateFragmentsVisibility(false);
421 updateNavigationElementsInActionBar(null);
422 }
423
424 protected void refeshListOfFilesFragment() {
425 OCFileListFragment fileListFragment = getListOfFilesFragment();
426 if (fileListFragment != null) {
427 fileListFragment.listDirectory();
428 }
429 }
430
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;
440
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);
445
446 } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
447 // update the right panel
448 boolean detailsFragmentChanged = false;
449 if (waitedPreview) {
450 if (success) {
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;
455 } else {
456 openFile(mWaitingToPreview);
457 }
458 }
459 mWaitingToPreview = null;
460 }
461 if (!detailsFragmentChanged) {
462 detailsFragment.updateFileDetails(false, (success));
463 }
464 }
465 }
466 }
467
468
469 @Override
470 public boolean onCreateOptionsMenu(Menu menu) {
471 MenuInflater inflater = getSherlock().getMenuInflater();
472 inflater.inflate(R.menu.main_menu, menu);
473 return true;
474 }
475
476 @Override
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");
483 break;
484 }
485 case R.id.action_sync_account: {
486 startSynchronization();
487 break;
488 }
489 case R.id.action_upload: {
490 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
491 break;
492 }
493 case R.id.action_settings: {
494 Intent settingsIntent = new Intent(this, Preferences.class);
495 startActivity(settingsIntent);
496 break;
497 }
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)) {
503 onBackPressed();
504
505 }
506 break;
507 }
508 default:
509 retval = super.onOptionsItemSelected(item);
510 }
511 return retval;
512 }
513
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(
524 getAccount(),
525 MainApp.getAuthority(), bundle);
526 } else {
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);
532 builder.syncOnce();
533 SyncRequest request = builder.build();
534 ContentResolver.requestSync(request);
535 }
536 }
537
538
539 @Override
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;
545 }
546 targetPath = OCFile.PATH_SEPARATOR + targetPath;
547 OCFile targetFolder = mStorageManager.getFileByPath(targetPath);
548 if (targetFolder != null) {
549 browseTo(targetFolder);
550 }
551
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);
556 }
557 return true;
558 }
559
560 /**
561 * Called, when the user selected something for uploading
562 */
563 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
564 super.onActivityResult(requestCode, resultCode, data);
565
566 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
567 requestSimpleUpload(data, resultCode);
568
569 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
570 requestMultipleUpload(data, resultCode);
571
572 }
573 }
574
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);
582 }
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();
587 }
588
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);
596 startService(i);
597
598 } else {
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);
601 t.show();
602 return;
603 }
604 }
605
606
607 private void requestSimpleUpload(Intent data, int resultCode) {
608 String filepath = null;
609 try {
610 Uri selectedImageUri = data.getData();
611
612 String filemanagerstring = selectedImageUri.getPath();
613 String selectedImagePath = getPath(selectedImageUri);
614
615 if (selectedImagePath != null)
616 filepath = selectedImagePath;
617 else
618 filepath = filemanagerstring;
619
620 } catch (Exception e) {
621 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
622 e.printStackTrace();
623
624 } finally {
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);
628 t.show();
629 return;
630 }
631 }
632
633 Intent i = new Intent(this, FileUploader.class);
634 i.putExtra(FileUploader.KEY_ACCOUNT,
635 getAccount());
636 String remotepath = new String();
637 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
638 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
639 }
640 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
641 remotepath += OCFile.PATH_SEPARATOR;
642 remotepath += new File(filepath).getName();
643
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);
649 startService(i);
650 }
651
652 @Override
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) {
658 finish();
659 return;
660 }
661 int levelsUp = listOfFiles.onBrowseUp();
662 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
663 popDirname();
664 }
665 }
666 }
667 if (listOfFiles != null) { // should never be null, indeed
668 setFile(listOfFiles.getCurrentFile());
669 }
670 cleanSecondFragment();
671
672 }
673
674 @Override
675 protected void onSaveInstanceState(Bundle outState) {
676 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
677 Log_OC.e(TAG, "onSaveInstanceState() start");
678 super.onSaveInstanceState(outState);
679 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
680 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
681 outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
682
683 Log_OC.d(TAG, "onSaveInstanceState() end");
684 }
685
686
687
688 @Override
689 protected void onResume() {
690 super.onResume();
691 Log_OC.e(TAG, "onResume() start");
692
693 // Listen for sync messages
694 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.getSyncMessage());
695 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
696 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
697
698 // Listen for upload messages
699 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
700 mUploadFinishReceiver = new UploadFinishReceiver();
701 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
702
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);
708
709 Log_OC.d(TAG, "onResume() end");
710 }
711
712
713 @Override
714 protected void onPause() {
715 super.onPause();
716 Log_OC.e(TAG, "onPause() start");
717 if (mSyncBroadcastReceiver != null) {
718 unregisterReceiver(mSyncBroadcastReceiver);
719 mSyncBroadcastReceiver = null;
720 }
721 if (mUploadFinishReceiver != null) {
722 unregisterReceiver(mUploadFinishReceiver);
723 mUploadFinishReceiver = null;
724 }
725 if (mDownloadFinishReceiver != null) {
726 unregisterReceiver(mDownloadFinishReceiver);
727 mDownloadFinishReceiver = null;
728 }
729
730 Log_OC.d(TAG, "onPause() end");
731 }
732
733
734 @Override
735 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
736 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
737 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
738 }
739 }
740
741
742 @Override
743 protected Dialog onCreateDialog(int id) {
744 Dialog dialog = null;
745 AlertDialog.Builder builder;
746 switch (id) {
747 case DIALOG_SHORT_WAIT: {
748 ProgressDialog working_dialog = new ProgressDialog(this);
749 working_dialog.setMessage(getResources().getString(
750 R.string.wait_a_moment));
751 working_dialog.setIndeterminate(true);
752 working_dialog.setCancelable(false);
753 dialog = working_dialog;
754 break;
755 }
756 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
757
758 String[] items = null;
759
760 String[] allTheItems = { getString(R.string.actionbar_upload_files),
761 getString(R.string.actionbar_upload_from_apps),
762 getString(R.string.actionbar_failed_instant_upload) };
763
764 String[] commonItems = { getString(R.string.actionbar_upload_files),
765 getString(R.string.actionbar_upload_from_apps) };
766
767 if (InstantUploadActivity.IS_ENABLED)
768 items = allTheItems;
769 else
770 items = commonItems;
771
772 builder = new AlertDialog.Builder(this);
773 builder.setTitle(R.string.actionbar_upload);
774 builder.setItems(items, new DialogInterface.OnClickListener() {
775 public void onClick(DialogInterface dialog, int item) {
776 if (item == 0) {
777 // if (!mDualPane) {
778 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
779 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
780 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
781 // } else {
782 // TODO create and handle new fragment
783 // LocalFileListFragment
784 // }
785 } else if (item == 1) {
786 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
787 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
788 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
789 ACTION_SELECT_CONTENT_FROM_APPS);
790 } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
791 Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
792 action.putExtra(FileUploader.KEY_ACCOUNT, FileDisplayActivity.this.getAccount());
793 startActivity(action);
794 }
795 }
796 });
797 dialog = builder.create();
798 break;
799 }
800 case DIALOG_SSL_VALIDATOR: {
801 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
802 break;
803 }
804 case DIALOG_CERT_NOT_SAVED: {
805 builder = new AlertDialog.Builder(this);
806 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
807 builder.setCancelable(false);
808 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
809 @Override
810 public void onClick(DialogInterface dialog, int which) {
811 dialog.dismiss();
812 };
813 });
814 dialog = builder.create();
815 break;
816 }
817 default:
818 dialog = null;
819 }
820
821 return dialog;
822 }
823
824
825 /**
826 * Show loading dialog
827 */
828 public void showLoadingDialog() {
829 // Construct dialog
830 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
831 FragmentManager fm = getSupportFragmentManager();
832 FragmentTransaction ft = fm.beginTransaction();
833 loading.show(ft, DIALOG_WAIT_TAG);
834
835 }
836
837 /**
838 * Dismiss loading dialog
839 */
840 public void dismissLoadingDialog(){
841 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
842 if (frag != null) {
843 LoadingDialog loading = (LoadingDialog) frag;
844 loading.dismiss();
845 }
846 }
847
848
849 /**
850 * Translates a content URI of an image to a physical path
851 * on the disk
852 * @param uri The URI to resolve
853 * @return The path to the image or null if it could not be found
854 */
855 public String getPath(Uri uri) {
856 String[] projection = { MediaStore.Images.Media.DATA };
857 Cursor cursor = managedQuery(uri, projection, null, null, null);
858 if (cursor != null) {
859 int column_index = cursor
860 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
861 cursor.moveToFirst();
862 return cursor.getString(column_index);
863 }
864 return null;
865 }
866
867 /**
868 * Pushes a directory to the drop down list
869 * @param directory to push
870 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
871 */
872 public void pushDirname(OCFile directory) {
873 if(!directory.isFolder()){
874 throw new IllegalArgumentException("Only directories may be pushed!");
875 }
876 mDirectories.insert(directory.getFileName(), 0);
877 setFile(directory);
878 }
879
880 /**
881 * Pops a directory name from the drop down list
882 * @return True, unless the stack is empty
883 */
884 public boolean popDirname() {
885 mDirectories.remove(mDirectories.getItem(0));
886 return !mDirectories.isEmpty();
887 }
888
889 // Custom array adapter to override text colors
890 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
891
892 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
893 super(ctx, view);
894 }
895
896 public View getView(int position, View convertView, ViewGroup parent) {
897 View v = super.getView(position, convertView, parent);
898
899 ((TextView) v).setTextColor(getResources().getColorStateList(
900 android.R.color.white));
901 return v;
902 }
903
904 public View getDropDownView(int position, View convertView,
905 ViewGroup parent) {
906 View v = super.getDropDownView(position, convertView, parent);
907
908 ((TextView) v).setTextColor(getResources().getColorStateList(
909 android.R.color.white));
910
911 return v;
912 }
913
914 }
915
916 private class SyncBroadcastReceiver extends BroadcastReceiver {
917
918 /**
919 * {@link BroadcastReceiver} to enable syncing feedback in UI
920 */
921 @Override
922 public void onReceive(Context context, Intent intent) {
923 boolean inProgress = intent.getBooleanExtra(FileSyncService.IN_PROGRESS, false);
924 String accountName = intent.getStringExtra(FileSyncService.ACCOUNT_NAME);
925 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
926
927 if (getAccount() != null && accountName.equals(getAccount().name)
928 && mStorageManager != null
929 ) {
930
931 /// get the shared files
932 if (isSharedSupported()) {
933 startGetSharedFiles();
934 }
935
936 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
937
938 OCFile currentFile = (getFile() == null) ? null : mStorageManager.getFileByPath(getFile().getRemotePath());
939 OCFile currentDir = (getCurrentDir() == null) ? null : mStorageManager.getFileByPath(getCurrentDir().getRemotePath());
940
941 if (currentDir == null) {
942 // current folder was removed from the server
943 Toast.makeText( FileDisplayActivity.this,
944 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
945 Toast.LENGTH_LONG)
946 .show();
947 browseToRoot();
948
949 } else {
950 if (currentFile == null && !getFile().isFolder()) {
951 // currently selected file was removed in the server, and now we know it
952 cleanSecondFragment();
953 currentFile = currentDir;
954 }
955
956 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
957 OCFileListFragment fileListFragment = getListOfFilesFragment();
958 if (fileListFragment != null) {
959 fileListFragment.listDirectory(currentDir);
960 }
961 }
962 setFile(currentFile);
963 }
964
965 if (!mRefreshSharesInProgress) {
966 setSupportProgressBarIndeterminateVisibility(inProgress);
967 } else {
968 setSupportProgressBarIndeterminateVisibility(true);
969 }
970
971 removeStickyBroadcast(intent);
972 mSyncInProgress = inProgress;
973
974 }
975
976 if (synchResult != null) {
977 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
978 mLastSslUntrustedServerResult = synchResult;
979 showDialog(DIALOG_SSL_VALIDATOR);
980 }
981 }
982 }
983 }
984
985
986 private class UploadFinishReceiver extends BroadcastReceiver {
987 /**
988 * Once the file upload has finished -> update view
989 * @author David A. Velasco
990 * {@link BroadcastReceiver} to enable upload feedback in UI
991 */
992 @Override
993 public void onReceive(Context context, Intent intent) {
994 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
995 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
996 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
997 OCFile currentDir = getCurrentDir();
998 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
999 if (sameAccount && isDescendant) {
1000 refeshListOfFilesFragment();
1001 }
1002 }
1003
1004 }
1005
1006
1007 /**
1008 * Class waiting for broadcast events from the {@link FielDownloader} service.
1009 *
1010 * Updates the UI when a download is started or finished, provided that it is relevant for the
1011 * current folder.
1012 */
1013 private class DownloadFinishReceiver extends BroadcastReceiver {
1014 @Override
1015 public void onReceive(Context context, Intent intent) {
1016 boolean sameAccount = isSameAccount(context, intent);
1017 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1018 boolean isDescendant = isDescendant(downloadedRemotePath);
1019
1020 if (sameAccount && isDescendant) {
1021 refeshListOfFilesFragment();
1022 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1023 }
1024
1025 removeStickyBroadcast(intent);
1026 }
1027
1028 private boolean isDescendant(String downloadedRemotePath) {
1029 OCFile currentDir = getCurrentDir();
1030 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1031 }
1032
1033 private boolean isSameAccount(Context context, Intent intent) {
1034 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1035 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1036 }
1037 }
1038
1039
1040 /**
1041 * {@inheritDoc}
1042 */
1043 @Override
1044 public FileDataStorageManager getStorageManager() {
1045 return mStorageManager;
1046 }
1047
1048
1049 public void browseToRoot() {
1050 OCFileListFragment listOfFiles = getListOfFilesFragment();
1051 if (listOfFiles != null) { // should never be null, indeed
1052 while (mDirectories.getCount() > 1) {
1053 popDirname();
1054 }
1055 OCFile root = mStorageManager.getFileByPath(OCFile.ROOT_PATH);
1056 listOfFiles.listDirectory(root);
1057 setFile(listOfFiles.getCurrentFile());
1058 startSyncFolderOperation(root);
1059 }
1060 cleanSecondFragment();
1061 }
1062
1063
1064 public void browseTo(OCFile folder) {
1065 if (folder == null || !folder.isFolder()) {
1066 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1067 }
1068 OCFileListFragment listOfFiles = getListOfFilesFragment();
1069 if (listOfFiles != null) {
1070 setNavigationListWithFolder(folder);
1071 listOfFiles.listDirectory(folder);
1072 setFile(listOfFiles.getCurrentFile());
1073 startSyncFolderOperation(folder);
1074 } else {
1075 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1076 }
1077 cleanSecondFragment();
1078 }
1079
1080
1081 /**
1082 * {@inheritDoc}
1083 *
1084 * Updates action bar and second fragment, if in dual pane mode.
1085 */
1086 @Override
1087 public void onBrowsedDownTo(OCFile directory) {
1088 pushDirname(directory);
1089 cleanSecondFragment();
1090
1091 // Sync Folder
1092 startSyncFolderOperation(directory);
1093
1094 }
1095
1096 /**
1097 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1098 *
1099 * @param file Image {@link OCFile} to show.
1100 */
1101 @Override
1102 public void startImagePreview(OCFile file) {
1103 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1104 showDetailsIntent.putExtra(EXTRA_FILE, file);
1105 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1106 startActivity(showDetailsIntent);
1107 }
1108
1109 /**
1110 * Stars the preview of an already down media {@link OCFile}.
1111 *
1112 * @param file Media {@link OCFile} to preview.
1113 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1114 * @param autoplay When 'true', the playback will start without user interactions.
1115 */
1116 @Override
1117 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1118 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1119 setSecondFragment(mediaFragment);
1120 updateFragmentsVisibility(true);
1121 updateNavigationElementsInActionBar(file);
1122 setFile(file);
1123 }
1124
1125 /**
1126 * Requests the download of the received {@link OCFile} , updates the UI
1127 * to monitor the download progress and prepares the activity to preview
1128 * or open the file when the download finishes.
1129 *
1130 * @param file {@link OCFile} to download and preview.
1131 */
1132 @Override
1133 public void startDownloadForPreview(OCFile file) {
1134 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1135 setSecondFragment(detailFragment);
1136 mWaitingToPreview = file;
1137 requestForDownload();
1138 updateFragmentsVisibility(true);
1139 updateNavigationElementsInActionBar(file);
1140 setFile(file);
1141 }
1142
1143
1144 /**
1145 * Shows the information of the {@link OCFile} received as a
1146 * parameter in the second fragment.
1147 *
1148 * @param file {@link OCFile} whose details will be shown
1149 */
1150 @Override
1151 public void showDetails(OCFile file) {
1152 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1153 setSecondFragment(detailFragment);
1154 updateFragmentsVisibility(true);
1155 updateNavigationElementsInActionBar(file);
1156 setFile(file);
1157 }
1158
1159
1160 /**
1161 * TODO
1162 */
1163 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1164 ActionBar actionBar = getSupportActionBar();
1165 if (chosenFile == null || mDualPane) {
1166 // only list of files - set for browsing through folders
1167 OCFile currentDir = getCurrentDir();
1168 actionBar.setDisplayHomeAsUpEnabled(currentDir != null && currentDir.getParentId() != 0);
1169 actionBar.setDisplayShowTitleEnabled(false);
1170 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1171 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1172
1173 } else {
1174 actionBar.setDisplayHomeAsUpEnabled(true);
1175 actionBar.setDisplayShowTitleEnabled(true);
1176 actionBar.setTitle(chosenFile.getFileName());
1177 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1178 }
1179 }
1180
1181
1182 /**
1183 * {@inheritDoc}
1184 */
1185 @Override
1186 public void onFileStateChanged() {
1187 refeshListOfFilesFragment();
1188 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1189 }
1190
1191
1192 /**
1193 * {@inheritDoc}
1194 */
1195 @Override
1196 public FileDownloaderBinder getFileDownloaderBinder() {
1197 return mDownloaderBinder;
1198 }
1199
1200
1201 /**
1202 * {@inheritDoc}
1203 */
1204 @Override
1205 public FileUploaderBinder getFileUploaderBinder() {
1206 return mUploaderBinder;
1207 }
1208
1209
1210 /** Defines callbacks for service binding, passed to bindService() */
1211 private class ListServiceConnection implements ServiceConnection {
1212
1213 @Override
1214 public void onServiceConnected(ComponentName component, IBinder service) {
1215 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1216 Log_OC.d(TAG, "Download service connected");
1217 mDownloaderBinder = (FileDownloaderBinder) service;
1218 if (mWaitingToPreview != null) {
1219 requestForDownload();
1220 }
1221
1222 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1223 Log_OC.d(TAG, "Upload service connected");
1224 mUploaderBinder = (FileUploaderBinder) service;
1225 } else {
1226 return;
1227 }
1228 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1229 OCFileListFragment listOfFiles = getListOfFilesFragment();
1230 if (listOfFiles != null) {
1231 listOfFiles.listDirectory();
1232 }
1233 FileFragment secondFragment = getSecondFragment();
1234 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1235 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1236 detailFragment.listenForTransferProgress();
1237 detailFragment.updateFileDetails(false, false);
1238 }
1239 }
1240
1241 @Override
1242 public void onServiceDisconnected(ComponentName component) {
1243 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1244 Log_OC.d(TAG, "Download service disconnected");
1245 mDownloaderBinder = null;
1246 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1247 Log_OC.d(TAG, "Upload service disconnected");
1248 mUploaderBinder = null;
1249 }
1250 }
1251 };
1252
1253
1254
1255 /**
1256 * Launch an intent to request the PIN code to the user before letting him use the app
1257 */
1258 private void requestPinCode() {
1259 boolean pinStart = false;
1260 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1261 pinStart = appPrefs.getBoolean("set_pincode", false);
1262 if (pinStart) {
1263 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1264 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1265 startActivity(i);
1266 }
1267 }
1268
1269
1270 @Override
1271 public void onSavedCertificate() {
1272 startSyncFolderOperation(getCurrentDir());
1273 }
1274
1275
1276 @Override
1277 public void onFailedSavingCertificate() {
1278 showDialog(DIALOG_CERT_NOT_SAVED);
1279 }
1280
1281
1282 /**
1283 * Updates the view associated to the activity after the finish of some operation over files
1284 * in the current account.
1285 *
1286 * @param operation Removal operation performed.
1287 * @param result Result of the removal.
1288 */
1289 @Override
1290 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1291 if (operation instanceof RemoveFileOperation) {
1292 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1293
1294 } else if (operation instanceof RenameFileOperation) {
1295 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1296
1297 } else if (operation instanceof SynchronizeFileOperation) {
1298 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1299
1300 } else if (operation instanceof CreateFolderOperation) {
1301 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1302
1303 } else if (operation instanceof GetSharedFilesOperation) {
1304 onGetSharedFilesOperationFinish((GetSharedFilesOperation) operation, result);
1305 }
1306 }
1307
1308
1309 /** Updates the data about shared files
1310 *
1311 * @param operation Get Shared Files
1312 * @param result Result of the operation
1313 */
1314 private void onGetSharedFilesOperationFinish(GetSharedFilesOperation operation, RemoteOperationResult result) {
1315 // Refresh the filelist with the information
1316 refeshListOfFilesFragment();
1317
1318 mRefreshSharesInProgress = false;
1319
1320 if (!mSyncInProgress) {
1321 setSupportProgressBarIndeterminateVisibility(false);
1322 }
1323 }
1324
1325 /**
1326 * Updates the view associated to the activity after the finish of an operation trying to remove a
1327 * file.
1328 *
1329 * @param operation Removal operation performed.
1330 * @param result Result of the removal.
1331 */
1332 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1333 dismissLoadingDialog();
1334 if (result.isSuccess()) {
1335 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1336 msg.show();
1337 OCFile removedFile = operation.getFile();
1338 getSecondFragment();
1339 FileFragment second = getSecondFragment();
1340 if (second != null && removedFile.equals(second.getFile())) {
1341 cleanSecondFragment();
1342 }
1343 if (mStorageManager.getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1344 refeshListOfFilesFragment();
1345 }
1346
1347 } else {
1348 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1349 msg.show();
1350 if (result.isSslRecoverableException()) {
1351 mLastSslUntrustedServerResult = result;
1352 showDialog(DIALOG_SSL_VALIDATOR);
1353 }
1354 }
1355 }
1356
1357 /**
1358 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1359 *
1360 * @param operation Creation operation performed.
1361 * @param result Result of the creation.
1362 */
1363 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1364 if (result.isSuccess()) {
1365 dismissLoadingDialog();
1366 refeshListOfFilesFragment();
1367
1368 } else {
1369 dismissLoadingDialog();
1370 if (result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME) {
1371 Toast.makeText(FileDisplayActivity.this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG).show();
1372 } else {
1373 try {
1374 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
1375 msg.show();
1376
1377 } catch (NotFoundException e) {
1378 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1379 }
1380 }
1381 }
1382 }
1383
1384
1385 /**
1386 * Updates the view associated to the activity after the finish of an operation trying to rename a
1387 * file.
1388 *
1389 * @param operation Renaming operation performed.
1390 * @param result Result of the renaming.
1391 */
1392 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1393 dismissLoadingDialog();
1394 OCFile renamedFile = operation.getFile();
1395 if (result.isSuccess()) {
1396 if (mDualPane) {
1397 FileFragment details = getSecondFragment();
1398 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1399 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1400 }
1401 }
1402 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1403 refeshListOfFilesFragment();
1404 }
1405
1406 } else {
1407 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1408 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1409 msg.show();
1410 // TODO throw again the new rename dialog
1411 } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) {
1412 Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG);
1413 msg.show();
1414 } else {
1415 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1416 msg.show();
1417 if (result.isSslRecoverableException()) {
1418 mLastSslUntrustedServerResult = result;
1419 showDialog(DIALOG_SSL_VALIDATOR);
1420 }
1421 }
1422 }
1423 }
1424
1425
1426 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1427 dismissLoadingDialog();
1428 OCFile syncedFile = operation.getLocalFile();
1429 if (!result.isSuccess()) {
1430 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1431 Intent i = new Intent(this, ConflictsResolveActivity.class);
1432 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1433 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1434 startActivity(i);
1435
1436 }
1437
1438 } else {
1439 if (operation.transferWasRequested()) {
1440 refeshListOfFilesFragment();
1441 onTransferStateChanged(syncedFile, true, true);
1442
1443 } else {
1444 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1445 msg.show();
1446 }
1447 }
1448 }
1449
1450
1451 /**
1452 * {@inheritDoc}
1453 */
1454 @Override
1455 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1456 if (mDualPane) {
1457 FileFragment details = getSecondFragment();
1458 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1459 if (downloading || uploading) {
1460 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1461 } else {
1462 ((FileDetailFragment)details).updateFileDetails(false, true);
1463 }
1464 }
1465 }
1466 }
1467
1468
1469 public void onDismiss(EditNameDialog dialog) {
1470 if (dialog.getResult()) {
1471 String newDirectoryName = dialog.getNewFilename().trim();
1472 Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1473 if (newDirectoryName.length() > 0) {
1474 String path = getCurrentDir().getRemotePath();
1475
1476 // Create directory
1477 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1478 RemoteOperation operation = new CreateFolderOperation(path, false, mStorageManager);
1479 operation.execute( getAccount(),
1480 FileDisplayActivity.this,
1481 FileDisplayActivity.this,
1482 mHandler,
1483 FileDisplayActivity.this);
1484
1485 showLoadingDialog();
1486 }
1487 }
1488 }
1489
1490
1491 private void requestForDownload() {
1492 Account account = getAccount();
1493 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1494 Intent i = new Intent(this, FileDownloader.class);
1495 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1496 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1497 startService(i);
1498 }
1499 }
1500
1501
1502 private OCFile getCurrentDir() {
1503 OCFile file = getFile();
1504 if (file != null) {
1505 if (file.isFolder()) {
1506 return file;
1507 } else if (mStorageManager != null) {
1508 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1509 return mStorageManager.getFileByPath(parentPath);
1510 }
1511 }
1512 return null;
1513 }
1514
1515 public void startSyncFolderOperation(OCFile folder) {
1516 long currentSyncTime = System.currentTimeMillis();
1517
1518 mSyncInProgress = true;
1519
1520 // perform folder synchronization
1521 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1522 currentSyncTime,
1523 false,
1524 getStorageManager(),
1525 getAccount(),
1526 getApplicationContext()
1527 );
1528 synchFolderOp.execute(getAccount(), this, null, null, this);
1529
1530 setSupportProgressBarIndeterminateVisibility(true);
1531 }
1532
1533
1534 private void startGetSharedFiles() {
1535 // Get shared files/folders
1536 AccountManager accountMngr = AccountManager.get(this);
1537 String urlServer = accountMngr.getUserData(getAccount(), OwnCloudAccount.Constants.KEY_OC_BASE_URL);
1538
1539 RemoteOperation getSharedFiles = new GetSharedFilesOperation(urlServer, mStorageManager);
1540 getSharedFiles.execute(getAccount(), this, this, mHandler, this);
1541
1542 mRefreshSharesInProgress = true;
1543 setSupportProgressBarIndeterminateVisibility(true);
1544
1545 }
1546
1547 // public void enableDisableViewGroup(ViewGroup viewGroup, boolean enabled) {
1548 // int childCount = viewGroup.getChildCount();
1549 // for (int i = 0; i < childCount; i++) {
1550 // View view = viewGroup.getChildAt(i);
1551 // view.setEnabled(enabled);
1552 // view.setClickable(!enabled);
1553 // if (view instanceof ViewGroup) {
1554 // enableDisableViewGroup((ViewGroup) view, enabled);
1555 // }
1556 // }
1557 // }
1558 }