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