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