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