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