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